Sunday, September 4, 2011

Auto-Implemented Properties in C# 3.0

This is one of the productive changes in C# 3.0 which makes your code more readable without writing more lines for implementing properties. In C# 2.0, we implement properties with get and set accessors for returning (get) a private member’s value and for setting (set) a private members value, like as follows:
 
   class Customer
   {
        private string customerID;
        public string CustomerID
        {
            get { return customerID; }
            set { customerID = value; }
        }
 
        private string contactName;
        public string ContactName
        {
            get { return contactName; }
            set { contactName = value; }
        }
 
        private string city;
        public string City
        {
            get { return city; }
            set { city = value; }
        }
   }
 
So, in the above code you have declared three properties, every time doing the same thing i.e. returning and setting a private members value, which reduces the readability of the code.
 
But in C# 3.0 the same pattern can be implemented in a better way like follows:
 
   class Customer
   {
        public string CustomerID { get; set; }
        public string ContactName { get; set; }
        public string City { get; set; }
   }
 
For the above given code C# Compiler will automatically generate backing fields.
 
But there is a limitation i.e. when we use this kind of syntax for implementing properties we have to implement both get and set accessors.
 
Whereas we can use modifiers today also with Auto implemented properties i.e. you can have properties as follows:
 
   public string CustomerID { get; private set; }