Does anyone know what C# compiler does under the hood with the following code?
dict = new Dictionary<int, string>()
{
{ 1, "value1" },
{ 2, "value2" }
}
It is not clear to if it creates the KeyValuePair instances and call the Add method, or do something more optimized. Does anyone of you know it?
It’ll call the
Addmethod on the object with the values as arguments:The name
Addis hardcoded (specified in the C# spec: 7.5.10.3: Collection initializers). The number of arguments to the method is not limited. It just has to match the number of parameters of the method. Any collection (implementingIEnumerableinterface) that provides anAddmethod can be used like that.To further clarify, no, the compiler doesn’t really care that the class is a
Dictionaryto create aKeyValuePairand pass that toAdd. It simply generates a sequence of calls to theAddmethod passing all the arguments in each collection item in each call. TheAddmethod is responsible for the rest.