Sunday, September 4, 2011

Collection Initializers in C# 3.0

With C# 3.0, Collection Initializer is the combination of Collection Classes and Object Initializers. This feature is available for all the objects which are enumerable (i.e. they implement IEnumerable<T>) and have a public ‘Add’ Method to add the value.
   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; }
        }
   }
Using the above given class, if you want to create a List of Employees, then in C# 2.0 the code will be:
   List<CEmployee> Employees = new List<CEmployee>();
   CEmployee e1 = new CEmployee(101, "Rohit Sharma");
// If you have  implemented Constructor
   Employees.Add(e1);
And, if there is no Constructor, then:
   List<CEmployee> Employees = new List<CEmployee>();
   CEmployee e1 = new CEmployee();
   e1.EID = 1;
   e1.ENAME = "Ramesh Sachin";
   Employees.Add(e1);
This is for 1 Employee, now if you want to add 5 Employees, then you have to create them separately and add them in the list one by one.
But in C# 3.0, it is made easier, like below:
   List<CEmployee> Employees = new List<CEmployee>()
   {
        new CEmployee() { EID = 101, ENAME = "Goutham" },
        new CEmployee() { EID = 102, ENAME = "Virat" },
        new CEmployee() { EID = 103, ENAME = "Raina" },
        new CEmployee() { EID = 104, ENAME = "Isanth" },
        new CEmployee() { EID = 105, ENAME = "Mahendar" }
   };