Difference between Field and Property in C#

In C# language one of the common interview questions is, "What isthe difference b/w Field and Property in C#?".
In this blog I will explain some differences between field and property in C#.
  1. public class Person   
  2. {  
  3.     private int Id; //Field  
  4.     public int User_ID   
  5.   {   
  6.     //Property  
  7.         get   
  8.         {  
  9.             return Id;  
  10.         }  
  11.         set   
  12.         {  
  13.             Id = value;  
  14.         }  
  15.     }  
  16. }   
  1. 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 filed 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.

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

  3. Using property we can throw an event but this is not possible in field.
Example
  1. public class Person  
  2. {  
  3.     private int Id; //Field  
  4.     public int User_ID  
  5.   { //Property  
  6.         get   
  7.         {  
  8.             return Id;  
  9.         }  
  10.         set   
  11.         {  
  12.             valueChanged();  
  13.             Id = value;  
  14.         }  
  15.     }  
  16.     public void valueChanged()   
  17.     {  
  18.         //Write Code  
  19.     }  
  20. }  
Ebook Download
View all
Learn
View all