First, from the declaration of both, the public field is simply a simple public variable that the class exposes with the public modifier, and the property is the encapsulation of the field, which uses get and set accessors to control how the field values are set or returned.
because the essence of a property is a method (get or Set method ), There is no concept of attributes in IL. Therefore, for the common assignment and value operation in the development process, the use of public variables will certainly be faster than the use of properties, performance is slightly higher.
Although the public field is fast in speed, it must be open in the fields, so that the caller of the object can directly modify its value, whether the content of the value is legitimate, whether there is an error in the run, there is no guarantee, and thus greatly reduces the reusability of the class, instead, the property is similar to the method. It can handle the value of the stored variable , and if it is not legal, it can be transformed in place or warned directly. This is a great benefit for the use of objects of this class, and during the run, problems caused by errors in the values of the public variables are greatly reduced.
From the above content, both have advantages and disadvantages, in the actual project development process, we choose which way to use it?
If the following conditions are met, then we can boldly use public fields:
1. Allow free reading and writing;
2. The range of values is constrained only by the data type, without any other specific restrictions;
3. The change of value does not require the corresponding change of any other member in the class;
The use of a property is exactly the opposite of a variable, and a property should be used as long as any of the following conditions are true:
1. Required fields are read-only or write-only;
2. You need to limit the range of values for the field;
3. When changing the value of a field, you want to change some other state of the object;
Summary: Although public fields and properties can be used under appropriate conditions during the development of the actual project, we should use the property rather than the data member (field) as much as possible, and set all the fields as private fields, and if you want to expose them, encapsulate them as attributes. This is also the way Microsoft recommends.
The difference between the "go" attribute and the field