Home > Tutorial for Beginners > Collection Initializers in C# 3.0 | Basic Tutorial

Collection Initializers in C# 3.0 | Basic Tutorial

Collection Initializers is a new concept introduced in C# 3.0.  By implementing this concept in your code you can save your time for initializing individual property of your class.  In C# 2.0 you can initialize a collection you can use the following syntax.

public class Book
{
   public Book() { }

   public string BookName { get; set; }
   public string Price {get;set;}

}

And then you can add the items in collection objects as
// now create the object of Book Collection
   void InitilizeBookCollection()
   {
       List<Book> bookCollection = new List<Book>();
       bookCollection.Add(new Book { BookName = "C#", Price = "$250" });
       // and so on
   }

Just imagine if you have 3 more classes along with 10 properties, you have to spend lots of time to create the constructors don’t you? However in C# introduced a new concept called collection Initializers which is the extensions of object Initializers and helps developer to control their code easily. You can initialize your collections in a very fast and easy way. You can create instance of collection in a simple way. Objects those implemented System.Collections.Generic.ICollection<T> can use this features.
   

//object initilizers
       List<Book> bookCollection = new List<Book>()
           {
               new Book{ BookName="C#4.0", Price="$450"},
               new Book{ BookName="SQL 2010", Price="$250"},
               // and so on
           };

No need to use “Add” method in our collection. If you notice the code is also looks much clear and compact.

Post Comments Below

  1. No comments yet.
  1. No trackbacks yet.