Pages

Tuesday, 15 December 2020

Field and Property in Xamarin-C#

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.

Fields are normal variable members of a class. Generally, you should declare your fields as private, then use Properties to get and set their values. By this way you won’t affect their values them directly. This is common case practice since having public members violates the Encapsulation concept in OOP.

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 below 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.

Ex: 

  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. }  


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.

  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. }  

1 comment:

  1. Thank you for your post. This is excellent information. It is amazing and wonderful to visit your site. For more info:- Xamarin App Development

    ReplyDelete