Why is Dictionary transformed into a KeyValuePair here?

You are calling the enumerator of the Dictionary by calling foreach - and the foreach will give you access to the elements.

This is by design; see msdn.

foreach (var element in enumerable)

The compiler is trying to tell you that you're trying to squeeze the whole dictionary in a single element: the Key ValuePair. (note; this is an analogy: the actual reason is about type mismatch, not about size. C# is type safe which means you can only assign something to a type which has the same - possibly through inheritance - type)

Similar as if you foreach over an int[] array, the element in the loop will be an int, and not the array itself, int[].

So, for your code:

Your method is of type Dictionary<>:

//the Dictionary is enumerable 
//an element is the KeyValuePair
Dictionary<string, int> operatii(int a, int b)

So, in the loop:

//  this should be an element    in    the enumeratable
foreach(Dictionary<string, int> dict in operatii(5, 6))

Or its equivalent:

var array = new int[] {1,2,3};

// element is of type ìnt`
foreach(int element in array)

To fix it:

foreach(KeyValuePair<string, int> dict in operatii(5, 6))

But how does C# know that this should've been a KeyValuePair?

Because Dictionary has a GetEnumerator method, and the foreach loop knows to use this method. The method represents a collection of KeyValuePair<TKey, TValue>, hence the compiler can generate the message.

Maybe I really meant to write Dictionary in there, and make the foreach run only once (because I only have one Dictionary).

Then you should have your method return a collection of dictionaries, not a single dictionary. Such as e.g. static List<Dictionary<string, int>> operatii(int a, int b).

Tags:

C#