Object Initializers in .NET framework (Part II- Collection Initializers)

Vishvvas
Posted by in .NET Framework category on for Intermediate level | Points: 250 | Views : 6320 red flag
Rating: 5 out of 5  
 2 vote(s)

Collection initializers are series of object initializers thus providing a shorthand method for initializing collections. Its very useful feature provided by C# 3.0 and needs to be utilized in conjunction with object initializers.

Objective


To explore the collection initializers in .NET framework.

Introduction


In the previous article “Object Initializers in C# (Part I)” http://www.dotnetfunda.com/articles/article1479-object-initializers-in-net-framework-part-i-.aspx we discussed the initializations of objects in .NET framework. We ran through different examples for usual initialization options as well as examples for object initializations. These initializers provide a mechanism to initialize a type or object in a declarative manner at the time of creation of object without explicitly invoking the constructor eliminating the need to change/add constructors or use setter way of initialization.

For this discussion, we would go through collections initializers which are applicable to collections types.

Collection classes are the specialized classes provided by .Net framework for data storage and retrieval which provides support for stacks, queues, lists, and hash tables. Most of these collection classes implement the same interfaces (ICollection, IComparer, IEnumerable, IList, IDictionary, and IDictionaryEnumerator and their generic equivalents). For more specialized data storage needs, these interfaces can be inherited to create new collection classes. The namespace “System.Collections” and “System.Colelctions.Generic” etc has definitions for collections classes and generic collections classes respectively. The commonly used collection types are array, arraylist, list, hashtable and dictionary, sorted collection types , Queue collection types, stack collection types, hashset collection type etc.

Collections initializers are nothing but a series of comma separated object initializers.

We would extend the types used in Part I for this and see the examples for List and Dictionary<TKey, TValue>

Description


Following is class Person

public class Person

    {

        public string FirstName { getset; }

        public string LastName { getset; }

        public string MiddleName { getset; }

     

        public int PersonId { getset; }

 

        public Person(string firstName, string lastName)

        {

            this.FirstName = firstName;

            this.LastName = lastName;

        }

}


Please keep a tab on the syntax for collection initializers. These uses the objects initialized through  initilizers added into a collection.

 

class Program

    {

static void Main(string[] args)// for Object Initializers

        {

             Console.WriteLine("*********************Object Initilizers****************************************");

//Implementation with List

             List<Person> personList = new List<Person>()

                {

                  new Person {FirstName="Craig", LastName="McMillan"},

                  new Person {FirstName="Sachin", LastName="Tendulkar"},

                  new Person {FirstName="Roger", LastName="Federar"},

                  new Person {FirstName="Rajesh", LastName="Khanna"}

                };

             foreach (Person person in personList)

             {

                 Console.WriteLine("Collection Initializers for 'List' : The person's name is  " + person.FirstName + " " + person.LastName );           

             }

             //Implementation with dictionary

             Dictionary<intPerson> personDictionary = new Dictionary<intPerson>()

                {

                    { 1, new Person {FirstName="Rajesh", LastName="Karnik"}},

                    { 2, new Person {FirstName="Kapil", LastName="Deo"}},

                    { 3, new Person {FirstName="Tom", LastName="Cruz"}}

                };

 

             for (int i = 1; i <= personDictionary.Count; i++ )

             {

                 Console.WriteLine("Collection Initializers for 'Dictionary' : The person's name is  " + personDictionary[i].FirstName + " " + personDictionary[i].LastName);

             }

           Console.WriteLine("*****************************************************************************");

        }

}


Output

Let’s run the program and see the output.

*********************Object Initilizers****************************************

Collection Initializers for 'List' : The person's name is  Craig McMillan

Collection Initializers for 'List' : The person's name is  Sachin Tendulkar

Collection Initializers for 'List' : The person's name is  Roger Federar

Collection Initializers for 'List' : The person's name is  Lalit Khanna

Collection Initializers for 'Dictionary' : The person's name is  Rajesh Karnik

Collection Initializers for 'Dictionary' : The person's name is  Kapil Deo

Collection Initializers for 'Dictionary' : The person's name is  Tom Cruz

*****************************************************************************

Summary & Conclusion


The output demonstrates the usage of collection initializers and their results. The use of collection initializers is easy and pretty straightforward. Intellisence helps to choose all the properties/ member variables for the object initializers which are public giving the user a definite control on his usage. Collection initializers sets the elements in the collection. If the default constructor is not provided or declared as private in the class, object initializers who require public access will fail and hence consequently the collection initializers will also fail.

The use of collection is omnipresent in any programs and .net framework provides plethora of options for collections. While using object initializers, the collection initializers are needed and C# 3.0 provides for that.

While using collection initializers, the C# compiler parses the initializer token i.e. {} into Add method of collection. The performance is equivalent with the case when the objects were added with normal Add methods and not to forget that all these statements/expressions results into same MSIL code.

Benefits:

  • Eliminates the need of constructor overload when the properties (not initialized through constructor)are to be initialized
  • Bypasses the need of recompiling (in already deployed types)when constructor would need to be added for initialization

In a way, collection initializers give a shorthand method for initialization of its members using the object initializers.

Happy Programming!!!!!


References

  • http:// msdn.microsoft.com/en-us/library/bb384062.aspx
  • http:// msdn.microsoft.com/en-us/library/bb397680.aspx

Page copy protected against web site content infringement by Copyscape

About the Author

Vishvvas
Full Name: Vishwas Sutar
Member Level: HonoraryPlatinum
Member Status: Member,MVP
Member Since: 5/30/2011 2:13:10 AM
Country: India

http://www.dotnetfunda.com
Extensive and rich experience across gamut of technologies and programming languages like PB,VB,C++,VB.NET, C#, Classic ASP,ASP.NET, ASP.NET MVC.

Login to vote for this post.

Comments or Responses

Posted by: SheoNarayan on: 7/26/2011 | Points: 25
Very good attempt to explain initializers by writing series of articles.

Keep it up Vishwas!
Posted by: Ashuthinks on: 7/26/2011 | Points: 25
useful demo ;)
thank you
Posted by: Akiii on: 7/26/2011 | Points: 25
Good article regarding initializers...

Thanks and Regards
Akiii

Login to post response

Comment using Facebook(Author doesn't get notification)