tags:

views:

95

answers:

1

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?

+8  A: 
Mehrdad Afshari
One very slight correction here - the variable isn't assigned until *after* all the Add calls. Basically it's as if there's a temporary variable. It's a nitpick, but hey - we're going for "under the covers" here :) (It wasn't worth a separate answer though.) You may also want to mention that the collection has to implement `IEnumerable`, even though there are no calls to `GetEnumerator()`.
Jon Skeet
More interesting background info here: http://blogs.msdn.com/b/madst/archive/2006/10/10/what-is-a-collection_3f00_.aspx
LukeH
@Jon: Interesting observation about the order. Fixed. Thanks. Added `IEnumerable` requirement too.
Mehrdad Afshari
I'll check the C# specification more often when I find myself wondering about the answer of this kind of question. Thanks for sharing the explatation about how collection initializers works was available there.
Carlos Loth