Monday, 5 September 2011

Collection Initializer in C# 3.0

Collection initializer is a new feature in c# 3.0. Using this feature an object can be added to a collection while collection is getting initiated. Collection initializer uses object initializer to add objects in collection on the fly.
  1. Collection initializer is new feature of C# 3.0
  2. Collection initializer gives a simple syntax to create instance of a collection.
  3. Any object that is implementing System.Collections.Generic.ICollection<T> can be initialized with collection initializer.
Let us say, we have a class:
public class Student
public string FirstName { get; set; }
      public string LastName { get; set; }
Now, if instance of Student class can be assigned to List of student at the time of creation of instance of list then we call it automatic collection initializer.
List<Student> lstStudent = newList<Student>()
        new Student {FirstName ="Dhananjay" ,LastName="Kumar"},
        new Student {FirstName ="Mritunjay", LastName ="Kumar"}

foreach (var r in lstStudent)
        Console.WriteLine(r.FirstName + “ – “ + r. LastName);

If we see the above syntax:
  1. It is highly readable.
  2. It is single statement.
  3. Instance of Student class is getting added on the fly.

No comments:

Post a Comment