300x250 AD TOP

helooo
Tagged under:

Fields and Properties




Fields are ordinary member variables or member instances of a class.
Properties are an abstraction to get and set their values.
Properties are also called accessors because they offer a way to change and retrieve a field if you expose a field in the class as private.
Generally, you should declare your member variables private, then declare or define properties for them. 
There are three obvious reasons for the necessity of properties in C#. 
1. You can delay the creation of actual reference fields until you use them, which saves resources
2. You can differentiate the representation and actual storage. Representation is implemented via properties and storage is implemented via fields.
3. You can check constraints when setting and getting properties. If the value is not suitable, you do not store the data in the field and a type-safety error is returned. This really provides 100% type-safe accessors on demand. 
Properties afford you the advantage of more elegant syntax along with the robustness and better 

encapsulation of accessor methods.
Below picture depicts how to use filed and property :

public class DemoClass
{
    //This is a Field (It is private to your class and stores the actual data)
    private string _DemoField;

    //This is a property.  When you access it uses the underlying field, but only exposes
    //the contract that will not be affected by the underlying field
    public string DemoField
    {
        get {
            return _DemoField;
        }
        set {
            _DemoField = value;
        }
    }
}