Why is it possible to initialize a Dictionary
like this:
var dict = new Dictionary() {
{ \"key1\", 1 },
{ \"
In case someone comes here, as I did, looking to save some keystrokes for the new C# 6.0 dictionary initializer syntax, it can be done, but requires deriving from IDictionary instead. You only need to implement the this[] set method to get this to work, which leaves a ton of non-implemented methods.
The class implementation looks like this:
// Seriously! Don't do this in production code! Ever!!!
public class CrazyAdd2 : IDictionary
{
public int this[string key]
{
get { throw new NotImplementedException(); }
set {Console.WriteLine($"([{key}]={value})"); }
}
#region NotImplemented
// lots of empty methods go here
#endregion
}
then to use it:
var crazyAdd2 = new CrazyAdd2
{
["one"] = 1,
["two"] = 2,
};
and the output:
([one]=1)
([two]=2)
And here's a fiddle demonstrating the whole thing:
https://dotnetfiddle.net/Lovy7m