How to initialize KeyValuePair object the proper way?
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?
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
Dictionaries have compact initializers:
var imgFormats = new Dictionary<string, ChartImageFormat>()
{
{".bmp", ChartImageFormat.Bmp},
{".gif", ChartImageFormat.Gif},
{".jpg", ChartImageFormat.Jpeg},
{".jpeg", ChartImageFormat.Jpeg},
{".png", ChartImageFormat.Png},
{".tiff", ChartImageFormat.Tiff},
};
In this case the dictionary i used to associate file extensions with image format constants of chart objects.
A single keyvaluepair can be returned from the dictionary like this:
var pair = imgFormats.First(p => p.Key == ".jpg");
KeyValuePair<int, int>
is a struct, and, fortunately, it is immutable struct. In particular, this means that its properties are read only. So, you can't use object intializer for them.