Wednesday, March 4, 2009

Automatic Properties – Features of C# 3.0 (Part - 2)

In the first part of this blog we saw Extension Methods. This blog will try to shed some light on another feature introduced in C# 3.0 called Automatic Properties.

What is Automatic Properties?

Imagine you have a Car class with ModelName, Color, NumberOfDoors, SeatingCapacity etc as their properties. Your typical class structure will look something shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AutomaticPropertyDemo
{  
    public class Car  
    {    
        private string _modelName;    
        private string _color;    
        private int _noOfDoors;    
        private int _seatingCapacity;    
        public string ModelName    
        {        
            get { return this._modelName; }        
            set { this._modelName = value; }    
        }    
        public string Color
        {
            get { return this._color; }        
            set { this._color = value; }    
        }    
        public int NumberOfDoors    
        {        
            get { return this._noOfDoors; }        
            set { this._noOfDoors = value; }    
        }    
        public int SeatingCapacity    
        {        
            get { return this._seatingCapacity; }        
            set { this._seatingCapacity = value; }    
        } 
    }
}

From the above code one can see, to implement a single property we have to declare a private variable, set the value to the variable using the “value” keyword in the set block and then finally use the return keyword to return the stored value. The same code applies to all the properties. Just to implement four properties I had to write nearly 62 lines of code. Huh, that’s a lot of code which doesn’t do anything great. And I hate to write these kind of code which dumb in nature.

When I started using properties in my early days of .NET career, I use to think, if the system can infer the exact type of the object passed in the “value” keyword in a property and appropriately cast it to the variable, then why can’t it infer the same using the property’ signature and automatically generate codes to assign and return the values of a property, after all the codes are pretty much same. And if there is a need to implement some logic inside the properties only then the user should write his/her own implementation of the get and set property. If you were also thinking the same then with C# 3.0 Microsoft has come up with Automatic Properties to help developers like you and me.

With automatic properties one need not declare a member variable to store the values of the properties and need not write the same code repeatedly again and again. The above code can be rewritten like the one shown below using automatic properties.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AutomaticPropertyDemo
{  
    public class Car  
    {    
        public string ModelName { get; set; }    
        public string Color { get; set; }    
        public int NumberOfDoors { get; set; }    
        public int SeatingCapacity { get; set; } 
    }
}

From the above code you can see the nearly 62 lines of code has been reduced to just 16 lines of code. There was no need to declare a member variable, no need to write the same repetitive code for assigning and returning the value. One has to just declare the property with a get and set key word. The only restriction which applies here is that automatic properties should have both getters and setters.

The next obvious question would be how would one can declare a get or set only property using automatic property. Its simple, qualify the set or get with the “private” access modifier. The below code shows the code snippet.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AutomaticPropertyDemo
{  
    public class Car  
    {    
        public string ModelName { get; set; }    
        public string Color { get; set; }    
        public int NumberOfDoors { get; private set; }    
        public int SeatingCapacity { private get; set; } 
    }
}

From the above code we can see the “NumberOfDoors” property has been declared as read only by qualifying the setter with private access modifier and the “SeatingCapacity” property is set only. In “SeatingCapacity” property the getter is declared private.With private or protected access modifier one can control the access level of automatic properties.

With automatic properties one need not write tons of code just to declare simple properties. With get and set keyword one can declare a read/write property. The compiler will auto create the variables necessary to store the values. If there is a need in future to bring in some logic to the setter and getter, one can very well extend the code without much work.

As quoted earlier it is a must to have both getter and setter in Automatic property. If either one, get or set, is missed the following error will be thrown by the compiler.

'AutomaticPropertyDemo.Car.Color.set' must declare a body because it is not marked abstract or extern. Automatically implemented properties must define both get and set accessors.

Many people have asked me how to access the automatically created variable? Why would anyone access the auto generated variable? The aim of automatic property is to write terse codes, if you want to desperately access the values stored in the property then access it using the property name. The only reasonable reason when you would need to access the auto generated variable is when you have some logic embedded inside the getter/setter method. If you have some logic, then obviously one cannot make use of automatic properties, one has to go by the good old way of declaring member variables and making use of it in properties. If one plans to bring in some logic then obviously he has to take full control of the properties by declaring member variables for the properties and should not rely on the system’ auto generated variables. I hope the above reasoning is enough for people who want to access auto generated variables and as far as my knowledge goes there is no way of doing that.

So what are you waiting for, start writing terse codes!!

Know more

Sandeep

6 comments:

  1. Can you use auto properties with generics such as a List

    Jeff

    ReplyDelete
  2. If I am not wrong you are asking whether we can use Automatic properties when the return type is a generic list? The answer is yes, you can use Automatic properties with generic list collection as well.

    ReplyDelete
  3. Hi Sandeep..The information posted here is very information. Please keep posting..the same...
    Cheers for your gud work.

    ReplyDelete
  4. Good post,it cleared my basic concept about this property
    thank you so much and keep posting.

    ReplyDelete

Please provide your valuable comments.