Sunday, September 4, 2011

Object Initializers in C# 3.0

Object Initializers
This change in C# 3.0 allows developers to get rid of the constructors they have to write in case of C# 2.0. Say for example in C# 2.0 if you have a class named CEmployee as follows:
   class CEmployee
   {
        private int EmpID;
        public int EID
        {
            get { return EmpID; }
            set { EmpID = value; }
        }
        private string EmpName;
        public string ENAME
        {
            get { return EmpName; }
            set { EmpName = value; }
        }
   }
Now, if you want to initialize the objects at the time of declaration, as follows:
   CEmployee obj1 = new CEmployee(101, "Rohit Sharma");
   CEmployee obj2 = new CEmployee(102);
   CEmployee obj3 = new CEmployee("Rahul");
To write the code shown in the lines above, the developer should write three parameterized constructors inside the CEmployee class as follows:
   public CEmployee(int id, string name)
   {
        EmpID = id;
        EmpName = name;
   }
   public CEmployee(int id)
   {
        EmpID = id;
   }
   public CEmployee(string name)
   {
        EmpName = name;
   }
However in C# 3.0, if you have created properties inside your class as in above given CEmployee class, you do not have to write the constructors anymore. So C# 3.0 gives you this enhancement to write it easily as follows:
   CEmployee obj1 = new CEmployee() { EID = 102, ENAME = "Rahul" };
   CEmployee obj2 = new CEmployee() { EID = 103 };
   CEmployee obj3 = new CEmployee() { ENAME = "Vijay Kumar" };
The above given lines of code are easier to read in respect with C# 2.0 code, but you have to write a bit more code.