Skip to content

Index initializers C# 6.0code reduction

Allow indexers to be set from object or collection initialization syntax.

Prior to this feature dictionaries had to be initialized with Add() calls or by using the collection initializer syntax with a necessary LINQ transformation.

Code

C#
var phonetics = new Dictionary<string, string>()
{
    ["A"] = "Alpha",
    ["B"] = "Bravo",
    ["C"] = "Charlie",
    ["D"] = "Delta",
    ["E"] = "Echo"
};
C#
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");
C#
var phonetics = new[]
    { "Alpha", "Bravo", "Charlie", "Delta", "Echo" }
    .ToDictionary(k => k.Substring(1), v => v);

Notes

  • When creating a dictionary if there is something on the value that can derive the key create an array of the values and then ToDictionary() with the key specification

More information