Related Posts with Thumbnails

Property in C# class

Monday, May 3, 2010

How do you access member variables of any class from outside the class ? In most of the languages including C++ , you will make the member variables public so that you can create an instance of the class and directly access the public fields, as shown below:


public class Car
{
 // private fields.
 public string color;

 // constructor
 public Car()
 {
 }
}

The above class has one public field : color. You may access this field from outside the class as shown below:

Car car = new Car();

car.color = "red";

string color = car.color;

But this is the old way ! This would still work with C#, but the suggested approach is to use "Property" instead of directly accessing member variables.

The following code snippet shows how to create "Property" in a class.

public class Car
{
 // private fields.
 private string color;

 // constructor
 public Car()
 {
 }

 public string Color
 {
  get
  {
   return color; // return the value from privte field.
  }
  set
  {
   color = value; // save value into private field.
  }
 }
}

The above class has one private field - color. Then we have one "Property" called 'Color', which is used to represent the private field. Note that the field is private and the Property is public. (We have used the same name with upper/lower case to represent the 'Property' and 'field', but you may give any name you want.)

Each property has two parts :

  • get





  • set





  • The get part is executed when you access the value of the Property as shown below:

    Car car = new Car();
    
    string color = car.Color;
    

    When executed, the above get accessor will return the value stored in the field 'color'.
    The set part is executed when you assign a value to the Property as shown below:

    Car car = new Car();
    
    car.Color = "RED";
    


    When executed, the above set accessor will assign the value "RED" to the private field 'color'. (Note that'value' is a keyword, which will have the value assigned to it.)
    So, what is the difference ?

    On the first look, there is no difference! You can achieve the same behaviour by writing 2 different methods ( like SetColor(...), GetColor() ).
    First advantage of using property is, code looks cleaner than having 2 separate methods. You can simply call a property as if it was a field in the class Well, then you may ask why make it 2 methods, we can make it a public field, so that we can access it by creating an instance of the class.
    The main advantage over using a Property instead of a public field is, with the property, you will get a chance to write few lines of code (if you want) in the get and set accessors. So, you can perform some validation or any other logic before returning any values or assigning to the private field.

    See the modifed class below:

    public class Car
    {
     // private fields.
      private string color;
    
     // constructor
     public Car()
     {
     }
    
     public string Color
     {
      get
      {
       if ( color == "" ) 
        return "GREEN";
       else
        return color;
      }
      set
      {
       if ( value == "" )
        thrown new Exception ("Wrong value.");
       else
        color = value;
      }
     }
    }

    Let us analyze the get part first. Here we are checking whether there is a valid value in the field 'color' before we return the value. If it is empty, we are getting a chance to return a default value 'Green'. This way, we can make sure that whoever calls the property 'Color' will always get a valid color, never an empty string.

    In the set part, we are doing a validation to make sure we always assign a a valid value to our field. If someone assign an empty string to the 'Color' property, he will get an exception (error).

    Car car = new Car();
    
    car.Color = "";


    The above code will throw an error because we are trying to assign an empty string and the set accessor will throw an error if it an empty string. This way, we can make sure that we allow only valid values to be assigned.
    So, i guess now you would appreciate the purpose of "Property". So, no more public fields! Always have private fields and write public properties as wrapper for them if required to expose them to outside the class.

    0 comments:

    Post a Comment

    Site Rate