Tuesday, March 20, 2018

Field and Property in C#

Object orientated programming principles say that the internal workings of a class should be hidden from the outside world. If you expose a field you're in essence exposing the internal implementation of the class. So we wrap the field using the property to hide the internal working of the class.

We can see that in the above code section we define property as public and field as private, so user can only access the property but internally we are using the field, such that provides a level of abstraction and hides the field from user access.

Another  important difference is that interfaces can have properties but not fields.

Using property we can throw an event but this is not possible in field.

A private field that stores the data exposed by a public property is called a backing store or backing field.

Code Snippet:

        public class Career
        {
            // field
            private int _path; 

            // Path is Property
            public int Path
            {
                get
                {
                    return _path;
                }
                set
                {
                    _path = value;
                }
            }
        }

No comments:

Post a Comment