Skip to content

Index initializers C# 6.0code reduction

Allow indexers to be set from object or collection initializers.

Prior to this feature dictionaries had to be initialized with Add() calls, either directly or through the { key, value } collection initializer C# 3.0 syntax which calls Add() for you.

C# 6.0 lets object initializers assign through an indexer using [key] = value, which works for any type with an indexer setter, not just dictionaries.

Code ​

csharp
var phonetics = new Dictionary<string, string>()
{
    ["A"] = "Alpha",
    ["B"] = "Bravo",
    ["C"] = "Charlie",
    ["D"] = "Delta",
    ["E"] = "Echo"
};
csharp
var phonetics = new Dictionary<string, string>()
{
    { "A", "Alpha" },
    { "B", "Bravo" },
    { "C", "Charlie" },
    { "D", "Delta" },
    { "E", "Echo" }
};
csharp
var phonetics = new Dictionary<string, string>();
phonetics.Add("A", "Alpha");
phonetics.Add("B", "Bravo");
phonetics.Add("C", "Charlie");
phonetics.Add("D", "Delta");
phonetics.Add("E", "Echo");

Notes ​

  • Index initializers call the indexer setter so a duplicate key silently overwrites the earlier value, whereas Add() (and therefore the { key, value } form) throws an ArgumentException
  • Index initializers cannot be mixed with { key, value } collection initializer entries in the same initializer
  • If the key can be derived from the value consider creating an array of the values and calling ToDictionary() with a key selector instead

More information ​

Powered by Intracia