Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens under the hood when using array initialization syntax to initialize a Dictionary instance on C#?

Tags:

c#

dictionary

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?

like image 489
CARLOS LOTH Avatar asked Dec 17 '25 18:12

CARLOS LOTH


1 Answers

It'll call the Add method on the object with the values as arguments:

var __temp = new Dictionary<int, string>();
__temp.Add(1, "value1");
__temp.Add(2, "value2");
dict = __temp;

The name Add is 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 (implementing IEnumerable interface) that provides an Add method can be used like that.

To further clarify, no, the compiler doesn't really care that the class is a Dictionary to create a KeyValuePair and pass that to Add. It simply generates a sequence of calls to the Add method passing all the arguments in each collection item in each call. The Add method is responsible for the rest.

like image 116
mmx Avatar answered Dec 20 '25 08:12

mmx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!