How to initialize KeyValuePair object the proper way?

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

Leave a Comment