C# 6 features – Index initializers


facebooktwittergoogle_pluslinkedinmail

A short one this time. You probably have seen object initializers. In C# 6 it’s extended to support indexing.

Here is an example of object initialization of a collection:

var dic = new Dictionary<int, string>
{
    { 1, "one" },
    { 4, "four" },
    { 10, "ten" }
};

This was possible even before C# 6. So what’s the difference? C# 6 extended it. Now you can use index initializers if a collection supports indexing.

var dic = new Dictionary<int, string>
{
    [1] = "one",
    [4] = "four",
    [10] = "ten"
};

I must admit that it even looks more intuitive in case of Dictionary class (comparing to first example).

facebooktwittergoogle_pluslinkedinmail

Leave a comment

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