Collection Initializer in C#

Collections initializers provide the fastest and easiest way to initialize a collection that implements IEnumerable. In a collection, the Add method is used to add items to a collection. 

The following code snippet creates a collection of "List<string>" and uses the Add method to add items to the collection. 

List<string> authors = new List<string>();
authors.Add("Mahesh Chand");
authors.Add("Raj Kumar");
authors.Add("Dinesh Beniwal");

We can simply replace the code above with the following code that uses a collection initializer approach and adds items to the collection during the creation of the collection object. 

 List<string> authors = new List<string>{
    "Mahesh Chand", "Raj Kumar", "Dinesh Beniwal"

This may not sound as attractive to you right now but when you're dealing with complex queries in LINQ. The object and collection initializers make developer's lives much easier. Not only do collection initializers make it easier to initialize collections but they also make code look cleaner and readable. 

The following code snippet lists an Author class with some public properties. 

public class Author
    public string Name { get; set; }
    public string Book { get; set; }
    public string publisher { get; set;}
    public Int16 Year { get; set; }
    public double Price { get; set; }

The following code creates a collection of Author objects using collection initializers. 

 List<Author> authors = new List<Author>{
    new Author(){ Name="Mahesh", Book="ADO.NET Programming", 
        publisher="Wrox", Year=2007, Price=44.95 }, 
    new Author(){ Name="Raj", Book="LINQ Cookbook", 
        publisher="APress", Year=2010, Price=49.95 },
    new Author(){ Name="Praveen", Book="XML Code", 
        publisher="Microsoft Press", Year=2012, Price=34.95 }

Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.