New C# Language Feature: Automatic Properties

This feature is supported in C# language only. Automatic properties provide a shorthand method for defining property procedures. Using Automatic properties, we can simplify writing property procedures.

Before understanding this feature, we will see what are property procedures in a class and how to write them using C#.

The syntax of an Item class without using Automatic properties is shown below.

class Item
{
    private string itemCode;
    private string itemName;
    private string itemdescription;
    private string itemCategory;
    private double itemPrice;
    private string itemUnit;

      public string Code { 
         get { return itemcode; }
         set { itemcode = value;  }
       }
       ......
}


For each property in the class, we need to write two blocks of code. One, is to set a value to the member variable (property) of the class and another is to retrieve data from the member variable. The code block used to retrieve data from the variable is called get accessor or getter and the code block used to assign a value to the property is called set accessor or setter.

Now, we will instantiate the Item class and assign values to properties.

The below statement creates an Item object.
Item myItem = new Item();   

In the below statement, we assign a value to the property procedure. When we do this, the value is assigned to the property itemCode.
myItem.Code ="I001";

The below code retrieves the data from the variable itemCode. This is because whenever we use the property in the code, the getter method will be executed automatically and value in the variable is retrieved.
string itemCode = myItem.Code ;
Console.WriteLine("itemCode : {0}", itemCode); 
Writing get and set code blocks for each and every property will become difficult when the class contains many properties. To overcome this problem, Microsoft has provided Automatic properties in C#. The syntax of an Item class using Automatic properties is shown below.

class Item
{
  public string Code 			{ get; set; }
  public string Name 			{ get; set; }
  public string description 	{ get; set; }
  public string Category 		{ get; set; }
  public double Price 			{ get; set; }
  public string Unit 			{ get; set; }  
}


As shown above, in the defintion of Automatic properties, we have not mentioned any field name.

Now, if we execute the below code, the output will be similar to the one without using Automatic properties.
Item myItem = new Item();   
myItem.Code="I001";
string itemCode =myItem.Code ;
Console.WriteLine("itemCode : {0}", itemCode);