#1,215 – C# 6.0 – New Syntax for Dictionary Initializers

Prior to C# 6.0, you could initialize a Dictionary object with a collection initializer as follows:

            // Initialization with collection initializer
            Dictionary<string, int> guys = new Dictionary<string, int> {
                {"Galileo", 1564},
                {"Magellan", 1480},
                {"Voltaire", 1694},
                {"Kepler", 1571},
                {"Keaton", 1895}
            };

In C# 6.0, the following syntax will also work:

            // Initialization with new dictionary initializer
            Dictionary<string, int> guys = new Dictionary<string, int>
            {
                ["Galileo"] = 1564,
                ["Magellan"] = 1480,
                ["Voltaire"] = 1694,
                ["Kepler"] = 1571,
                ["Keaton"] = 1895
            };

Note that as of 29 Oct, 2014, this feature is not enabled in the current Visual Studio 2014 CTP.

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

6 Responses to #1,215 – C# 6.0 – New Syntax for Dictionary Initializers

  1. wavecollapse says:

    Extra ‘}’ symbol here?

    [“Keaton”] = 1895}

  2. Vincent says:

    Just wondering… What’s the point of having a new syntax which is as verbose as previously ?

    • It looks more natural, I guess!

      • Vincent says:

        After little research, I found a benefit from this syntax:

        “However, a bigger advantage is that this syntax also provides the benefit of allowing you to initialize other types. Any type with an indexer will allow initialization via this syntax, where the old collection initializers only works with types that implement IEnumerable and have an Add method.”

        See the original post:

        http://stackoverflow.com/a/28076372/2065567

  3. Sean says:

    Excellent info, thanks Vincent

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: