Categories
csharp

Difference between property and field in C#

In C# different between fields and property of class, explained with example.

As per Object Oriented Programming principles internal of class should be hidden from outside world. So it is recommended to wrap fields of a class with properties, get,set in C# and keep fields private. By doing this object fields are safe and we can do some processing, event invocation, validation etc. while changing value of a field using properties or get set functions.

Here is sample for wrapping field into c# properties

    public class SampleClass
    {
        // this is a field.  It is private to your class and stores the actual data.
        private string _myField1;

        // 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 MyField1
        {
            get
            {
                return _myField1;
            }
            set
            {
                _myField1 = value;
                OnChangeField1();
            }
        }

        private void OnChangeField1()
        { 
            //Some code
        }
    }

In above code we can do processing and other code execution in get and set block.

In C# 3.0 AutoProperty is introduced in which we do not need to declare field separately, we have to just write property with modified syntax. C# 3.0 and above compiler will generate a private field automatically into compiled assembly.

Ref: http://msdn.microsoft.com/en-IN/library/bb384054.aspx

    public class SampleClass
    {
        public string MyField1
        {
            get;
            set;
        }
    }

Above two examples will produce same IL code.