Why is it possible to initialize a Dictionary
like this:
var dict = new Dictionary() {
{ \"key1\", 1 },
{ \"
Thanks to multiple answerers for pointing out that the Add method is the magical thing secret sauce that makes the initialization syntax work. So I could achieve my goal by inheriting the class in question (KeyValuePair):
public class InitializableKVPs : IEnumerable>
{
public void Add(T1 key, T2 value)
{
throw new NotImplementedException();
}
public IEnumerator> GetEnumerator()
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
This now is accepted by the compiler:
var kvps = new InitializableKVPs {
{ "key1", 1 },
{ "key2", 2 }
};
Edit: Philip Daubmeier's answer has an actual, concise implementation of this.