How to initialize KeyValuePair object the proper way?

c#, initialization

Solution

You are not wrong you have to initialise a keyValuePair using

KeyValuePair<int, int> keyValuePair = new KeyValuePair<int, int>(1, 2);

The reason that you cannot use the object initialisation syntax ie { Key = 1, Value = 2 } is because the Key and Value properties have no setters only getters (they are readonly). So you cannot even do:

keyValuePair.Value = 1; // not allowed

Problem

I've seen in (amongst others) this question that people wonder how to initialize an instance of KeyValuePair, which expectedly should look like this. ``` KeyValuePair<int, int> keyValuePair = new KeyValuePair<int, int> { Key = 1, Value = 2 }; ``` It doesn't work, as if the properties aren't there. Intead, I need to use the constructor like this. ``` KeyValuePair<int, int> keyValuePair = new KeyValuePair<int, int>(1, 2); ``` Admittedly shorter syntax but it bothers me that I can't use the initializer. What am I doing wrong?

Original source

Related problems