C# 3.0 – Part II :: Object & Collection Initializers

7 11 2008

In part I, the feature discussed was auto-implemented properties. Here we’ll make use of the classes defined in part I to demonstrate object initializers.

Notice that no constructor was declared in the classes defined. The compiler creates a default constructor (empty constructor), but this isn’t new in 3.0. What is new, is a way to set the properties of the object as it is initialized.

// declare and initialize an instance of the Address class
Address homeAddress = new Address()
{
// set the properties using C# 3.0 object initializer feature
Street = "123 Some Street",
City = "Newport Beach",
State = "CA",
PostalCode = "92626",
AddressType = AddressType.Home
};

We can then use the homeAddress instance to instantiate a Person object, also defined in part I.

Person person = new Person()
{
ID = 1,
FirstName = "John",
LastName = "Doe",
Addresses = new List<Address>(){ homeAddress }
};

Notice that we’ve initialized the collection of addresses of the person instance, as the object itself is initialized. Collection Initializers is also a new feature of C# 3.0. Instead of calling the Add method of a collection, we can simply list the objects, similar to that of arrays.

We can even combine the initialization of objects and collections into one big block of code.

Person person = new Person()
{
ID = 1,
FirstName = "John",
LastName = "Doe",
Addresses = new List<Address>()
{
new Address()
{
Street = "123 Some Street",
City = "Newport Beach",
State = "CA",
PostalCode = "92626",
AddressType = AddressType.Home
}}};

Probably the most interesting to me are the collection initializers. I’ve often have had to create lookup dictionaries for one reason or another. Typically the process is declare and instantiate the dictionary and then populate with lookup values.

Dictionary<int, string> numberLookup = new Dictionary()<int, string>();
numberLookup.Add(1, "one");
numberLookup.Add(2, "two");

Instead, we can instantiate like so:

Dictionary<int, string> numberLookup = new Dictionary()<int, string>()
{
{ 1, "one" },
{ 2, "two" }};


Actions

Information

Leave a comment