Properties are used to encapsulate some data. You can use a simple field:
public string MyField
But this field is available to all external users of your class. People can insert illegal values โโor change the value in ways you did not expect.
Using a property, you can encapsulate the way you access your data. C # has good syntax for turning a field into a property:
string MyProperty { get; set; }
This is called an automatically implemented property . When such a need arises, you can expand your property to:
string _myProperty; public string MyProperty { get { return _myProperty; } set { _myProperty = value; } }
Now you can add code that checks the value in your setter :
set { if (string.IsNullOrWhiteSpace(value)) throw new ArgumentNullException(); _myProperty = value; }
Properties can also have different accessors for getter and setter:
public string MyProperty { get; private set; }
This way you create a property that can be read by everyone, but can only be changed by the class itself.
You can also add a fully custom implementation for getter :
public string MyProperty { get { return DateTime.Now.Second.ToString(); } }
When C # compiles your automatically implemented property, it generates an intermediate language (IL). In your IL, you will see the get_MyProperty and set_MyProperty . It also creates a support field called <MyProperty>k_BackingField (usually it would be an illegal name in C #, but it is valid in IL. This way you will not get any conflicts between the generated types and your own code). However, you must use the official property syntax in C #. This creates a more enjoyable C # experience (e.g. with IntelliSense).
By convention, you should not use properties for operations that take a lot of time.
Wouter de Kort Jul 26 '13 at 12:30 2013-07-26 12:30
source share