var maxDictionary = new Dictionary<int, double> { { 10, 40000 } };
In the above code, does the compiler uses a constructor? Or does the compiler create a KeyValuePair and add to the dictionary? I'm trying to understand how the compiler interprets it.
Dictionaries are also initialized using the curly braces {} , and the key-value pairs are declared using the key:value syntax. You can also initialize an empty dictionary by using the in-built dict function. Empty dictionaries can also be initialized by simply using empty curly braces.
A dictionary, also called an associative array, is a collection of unique keys and a collection of values, where each key is associated with one value. Retrieving and adding values is very fast. Dictionaries take more memory because for each value there is also a key.
Syntax: public bool ContainsKey (TKey key); Here, the key is the Key which is to be located in the Dictionary. Return Value: This method will return true if the Dictionary contains an element with the specified key otherwise, it returns false.
Yes, compiler uses default parameterless constructor and then adds all values specified in collection initializer via Dictionary.Add method. As Jon pointed, your code is compiled into
Dictionary<int, double> maxDictionary2; Dictionary<int, double> maxDictionary; maxDictionary2 = new Dictionary<int, double>(); maxDictionary2.Add(10, 40000.0); maxDictionary = maxDictionary2;
Generated IL:
.maxstack 3 .locals init ( [0] class [mscorlib]Dictionary`2<int32, float64> maxDictionary, [1] class [mscorlib]Dictionary`2<int32, float64> maxDictionary2) L_0000: nop L_0001: newobj instance void [mscorlib]Dictionary`2<int32, float64>::.ctor() L_0006: stloc.1 L_0007: ldloc.1 L_0008: ldc.i4.s 10 L_000a: ldc.r8 40000 L_0013: callvirt instance void [mscorlib]Dictionary`2<int32, float64>::Add(!0, !1) L_0018: nop L_0019: ldloc.1 L_001a: stloc.0
I.e. created dictionary assigned to temporary variable maxDictionary2
, filled with values, and only then reference to created and filled dictionary is copied to maxDictionary
variable.
Keep in mind that you can specify any other constructor, if you don't want to use parammeterless one. E.g. you can use one which sets initial capacity:
var maxDictionary = new Dictionary<int, double>(10) { { 10, 40000 } };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With