Friday, 28 June 2013

Insight Properties in C#

Note: All this data has been copied from various sources for the purpose of knowledge sharing. Data content  can be either as it is or with little modification.
---------------------------------------------------------------------------------------------------------------------

In C#, properties are nothing but natural extension of data fields. They are usually known as 'smart fields' in C# community.


The general form of declaring a property is as follows.          

<acces_modifier> <return_type> <property_name>

private int myVar;
 
        public int MyProperty
        {
            get { return myVar; }
            set { myVar = value; }
        }

Since normal data fields and properties are stored in the same memory space, in C#, it is not possible to declare a field and property with the same name. 

Why we use properties.
There could be the confusion why we prefer properties when we can public fields instead. 
there are many reasons some of them are as follows. 
 1) properties allow for more error checking, among other things.
public Color Color
    {
        get {return _Color;}
        set
        {             if (value == Color.LimeGreen) throw new Exception("That is a rediculous color.");
            _Color = value;
        }
2)properties are more flexible than fields in that you can have read only properties, write only properties
3)properties that don't necessarily map to a single private field etc.
4) properties help in   triggering events on change of values of object members
bool started; public bool Started { get { return started; } set { started = value; if (started) OnStarted(EventArgs.Empty); } }
Interesting thing to know is that you can use methods just like properties although methods are generally about actions/behaviour and properties are about an objects data and hence its easier to catch at data level than at actions or behaviour level.

No comments:

Post a Comment