#1,215 – C# 6.0 – New Syntax for Dictionary Initializers
October 30, 2014 6 Comments
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.
Extra ‘}’ symbol here?
[“Keaton”] = 1895}
Good catch, thanks
Just wondering… What’s the point of having a new syntax which is as verbose as previously ?
It looks more natural, I guess!
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
Excellent info, thanks Vincent