BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 3.0+

C# Collection Initializers

C# 3.0 introduces collection initializers, giving a new syntax that permits collections to be declared and populated in a single statement. They can be combined with object initializers to provide an elegant syntax for creating a collection of objects.

Initialising Collections

When using arrays, you can declare a new array and fill it with values with a single statement. However, when using C# 2.0 or earlier versions, this cannot be achieved with collections. C# 3.0 and the .NET framework 3.0 introduce the collection initializers to permit this type of population.

Collection initializers provide syntactic sugar for all types that implement the IEnumerable interface and that include an Add method. The list of initial items is provided in a comma-delimited format within braces instead of, or in addition to, the parentheses containing any parameters required for the collection's constructor. The compiler converts the list of items into a series of calls to the new object's Add method.

The following sample code shows a collection initializer creating and populating an ArrayList. To execute this example, ensure that you include using System.Collections; in the code:

ArrayList integers = new ArrayList {1, 2, 3};

foreach (int i in integers)
{
    Console.WriteLine(i);
}

/* OUTPUT

1
2
3

*/

Collection initializers allow elegant code when used with object initializers. This combination permits a collection of custom objects to be created and populated in a single command. A example, you may create a simple class for holding the details of a person:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

With this class, and the inclusion of a using System.Collections.Generic; directive, you can create a collection using a command similar to the following. Note that the final item in the collection is null. This is acceptable if the Add method of the new object will accept null as a valid option.

List<Person> people = new List<Person>
{
    new Person{ FirstName="Bob", LastName="Brown", Age=30 },
    new Person{ FirstName="Sam", LastName="Smith", Age=18 },
    new Person{ FirstName="Ted", LastName="Green", Age=79 },
    null
};
10 December 2008