C# 6 Index Initializers

suggest change

Starting with C# 6, collections with indexers can be initialized by specifying the index to assign in square brackets, followed by an equals sign, followed by the value to assign.

Dictionary Initialization

An example of this syntax using a Dictionary:

var dict = new Dictionary<string, int>
{
    ["key1"] = 1,
    ["key2"] = 50
};

This is equivalent to:

var dict = new Dictionary<string, int>();
dict["key1"] = 1;
dict["key2"] = 50

The collection initializer syntax to do this before C# 6 was:

var dict = new Dictionary<string, int>
{
    { "key1", 1 },
    { "key2", 50 }
};

Which would correspond to:

var dict = new Dictionary<string, int>();
dict.Add("key1", 1);
dict.Add("key2", 50);

So there is a significant difference in functionality, as the new syntax uses the indexer of the initialized object to assign values instead of using its Add() method. This means the new syntax only requires a publicly available indexer, and works for any object that has one.

public class IndexableClass
{
    public int this[int index]
    {
        set 
        { 
            Console.WriteLine("{0} was assigned to index {1}", value, index);
        }
    }
}

var foo = new IndexableClass
{
    [0] = 10,
    [1] = 20
}

This would output:

10 was assigned to index 0 20 was assigned to index 1

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents