Home > Tutorial for Beginners > C# 3.0 Automatic properties

C# 3.0 Automatic properties

Automatic Property:
It’s a new feature in Asp.net. It was introduced with asp.net 3.5.  Prior to 3.5 it was mandatory to declare private variable of a property to hold the value. For example if you  have one property with the name of “YourName” in your class then prior to declare this property you have to have declare one private variable of the same data type which will hold the property value. See the below code

    private string Name;

    public string YourName

    {

        get { return Name; }

        set { this.Name = value; }

    }

This was really time consuming and irritating jobs for developer and every developer is frustrated with this kind of redundant codes. “Automatic Property” features, has solved this issue.  Now you can create your property as without declaring the private variable as 

public string YourName
   {
       get {}
       set {}
   }

 

Rest of thing will be handling by compiler. When you declare an auto implemented property, the compiler will automatically create a private field to hold the property value along with Getters and setters. I feel l this code is much easier to read and understand. You cannot create read-only or write-only property. Like VB6 we have property bag, which the typical use of automatic property in C#.

More Examples:

Old Way – C# 2.0:

public class Person 
{    
  
string _FirstName;
   string
_LastName;

   public string FirstName 
   {
       
get { return _FirstName; }
       
set { _FirstName = value; }
   }

   public string LastName 
   {
       
get { return _LastName; }
       
set { _LastName = value; }
   }
}

C# 3.0:

public class Person 
{    
  
public string FirstName  { get; set; }
  
public string LastName  { get; set; }
}

Post Comments Below

  1. No comments yet.
  1. No trackbacks yet.