Index initializers

This is one of a series of posts on some of the new features in C# 6.0, which was just released.

When Linq was added, a number of cool side-features ended up being added as well–these were things that were needed for Linq, but added value by themselves as well, such as extension methods and object initializers:

Person p = new Person() { Name = "Bob", 
    Birthday = new DateTime(2000,01,01) };

Likewise, you could also initialize collections:

List people = new List() { "Bob", "Fred", "George" };

But what you couldn’t do in this way, until now, was easily initialize a dictionary or other object that used indexers. Index initializers allow you to set values via the Indexer on an object:

Dictionary<string, int> nameToAge = new Dictionary<string, int>()
{
   ["Bob"] = 12,
   ["Fred"] = 20,
   ["George"] = 35
};

This adds some consistency to initialization, and also can be very helpful when you are using Linq and need to pass a new, but initialized, dictionary. You can also mix in initialization if your class supports an indexer along with other properties:

Person p = new Person()
{ 
  Name = "Bob", 
  Birthday = new DateTime(2000,01,01), 
  [0] = "123 Main Street" 
};

Yes, this is a terrible example. A better example would involve a dictionary-like class that also had some additional properties.

 

Here are links to posts about other new features in C# 6.0:

Leave a Reply

Your email address will not be published. Required fields are marked *

*