Reason for KeyNotFoundException exception in dictionary initialization

Following code

new Dictionary<string, List<int>> { ["a"] = {1}, }; 

Throws a KeyNotFoundException , although {1} is a perfectly well-formed array (that is, int[] a = {1,2,3,4} is valid code). Changing the TValue Dictionary to int[] gives the compilation time CS1061 , but this is not the case (note the added distribution of the new[] array):

 new Dictionary<string, IEnumerable<int>> { ["a"] = new[]{1}, }; 

Why is this happening?

+5
source share
1 answer

Your first part of the code uses a collection initializer that does not use a logical assignment, but instead is intended to call Add into an existing collection. In other words, it is:

 var x = new Dictionary<string, List<int>> { ["a"] = {1}, }; 

is equivalent to:

 var tmp = new Dictionary<string, List<int>>(); var list = tmp["a"]; list.Add(1); var x = tmp; 

Hopefully this is obvious from why the second extension line will throw an exception.

Part of your reasoning error:

although {1} is a pretty well-formed array

No no. The syntax {1} means different things in different contexts. In this case, it is the initializer of the collection. In a statement:

 int[] a = { 1, 2, 3, 4 }; 

it is an array initializer. This syntax only creates a new array in an array declaration or as part of an array creation expression, for example. new[] { 1, 2, 3, 4 } .

+11
source

Source: https://habr.com/ru/post/1259198/


All Articles