automatic properties


Automatic properties became available with C# 3.0.  They allow you to declare get / set properties without having to declare a private field.  The compiler generates the private field in the background.  These are appropriate for properties that do not have any content in the get / set blocks.  If you need to have content in your get/set blocks then you need to declare the private field like in the regular way.  Look at the following comparison between regular properties versus automatic properties:

Regular Get /Set properties:

public class Animal
{   
   string _Color;
   string _Age;
  

public string Color
   {
   get { return _Color; }
   set { _Color = value; }
   }


public string Age
   {
   get { return _Age; }
   set { _Age = value; }
   }
}

Automatic properties:

public class  Animal
{   
   public string Color{ get; set; }
    public string Age{ get; set; }
}

No comments:

Post a Comment