September 2, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

New in C# 3.0: Create and Initialize Collection Objects in One Step

  • May 19, 2006
  • By Vipul Patel
  • Send Email »
  • More Articles »

To recap a previous article, the new object initializer feature in C# 3.0 is a simple syntax that eases the construction and initialization of objects. Suppose you have a class, Student, that looks like this:

public class Student
{
   public string firstName;
   public string lastName;
}

You can create an object of this class by using object initializers as follows:

var student1 = new Student{firstName = "Bruce", lastName = "Willis"};

C# 3.0's new collection initializers operate in a similar manner. Any object that implements System.Collections.Generic.ICollection<T> can have its values initialized with a collection initializer.

A collection initializer is made up of the following:

  • A sequence of object initializers, enclosed by "{" and "}" tokens and separated by commas.
  • Element initializers, each of which specifies an element to be added to the collection object being added. (Element initializers cannot be assignment expressions in a collection initializer.)

How does it work? A collection initializer must observe the following rules:

  • The collection object to which a collection initializer is applied must be of a type that implements System.Collections.Generic.ICollection<T> for exactly one T.
  • An implicit conversion from the type of each element initializer to T must exist. A collection initializer invokes the ICollection<T>.Add(T) method for each specified element in order.

As an example, the following collection initializer creates and initializes a new collection of strings with three members "Alice", "Bob", and "Chris":

List<string> names = new List<string> { "Alice", "Bob", "Chris" };
Note: All the initialization values are of type string. Otherwise, you'd get a compiler error.

Collection Initializers in Action

Suppose you want to represent a class and its enrolled students. You can do this through collection initializers by using C# 3.0 code such as the following:

using System;
using System.Collections.Generic;
using System.Text;
using System.Query;
using System.Xml.XLinq;
using System.Data.DLinq;
namespace CollectionInitializer
{
   class Program
   {
      public class MyClass
      {
         public string nameofClass;
         public List<string> studentNames = new List<string>();
      }
      static void Main(string[] args)
      {
         var classes = new List<MyClass>
         {
            new MyClass
            {
               nameofClass = "Science",
               studentNames = {"Laura", "George"}
            },
            new MyClass
            {
               nameofClass = "Commerce",
               studentNames = {"Bill", "Hillary"}
            }
         };
      }
   }
}

If you have Visual Studio 2005 (any flavor) and the LINQ Preview installed, you can compile the above code in the IDE.

If you do not have VS 2005 but have the LINQ Preview installed, you can use the following command to compile the code from the command line:

C:\Program Files\LINQ Preview\Bin\Csc.exe
/reference:"C:\Program Files\LINQ Preview\Bin\System.Data.DLinq.dll"
/reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll
/reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll
/reference:"C:\Program Files\LINQ Preview\Bin\System.Query.dll"
/reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll
/reference:"C:\Program Files\LINQ Preview\Bin\System.Xml.XLinq.dll" Program.cs

Code Internals

Take a closer look at this snippet from the preceding C# 3.0 code:

var classes = new List<MyClass>
{
   new MyClass
   {
      nameofClass = "Science",
      studentNames = {"Laura", "George"}
   },
   new MyClass
   {
      nameofClass = "Commerce",
      studentNames = {"Bill", "Hillary"}
   }
};

To the compiler, it has the same effect as the following:

var classes = new List<MyClass>();
var __c1 = new MyClass ();
__c1.nameofClass = "Science";
__c1.studentNames.Add("Laura");
__c1.studentNames.Add("George");
classes.Add(__c1);
var __c2 = new MyClass();
__c2.nameofClass = "Commerce";
__c2.studentNames.Add("Bill");
__c2.studentNames.Add("Hillary");
classes.Add(__c2);

If you fire up ILDASM and open the compiled binary, you will see something similar to Figure 1.



Click here for a larger image.

Figure 1: Compiled Binary of Sample Code Snippet





Page 1 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel