default equals to null. And default(KeyValuePair<T,U>) is an actual KeyValuePair that contains null, null .
To add key-value pair in C# Dictionary, firstly declare a Dictionary. IDictionary<int, string> d = new Dictionary<int, string>(); Now, add elements with KeyValuePair. d.
The KeyValuePair class stores a pair of values in a single list with C#. Set KeyValuePair and add elements − var myList = new List<KeyValuePair<string, int>>(); // adding elements myList. Add(new KeyValuePair<string, int>("Laptop", 20)); myList.
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.
Ok you have the answers. As an alternative, I prefer factory pattern similar to Tuple
class, for type inference magic :)
public static class KeyValuePair
{
public static KeyValuePair<K, V> Create<K, V>(K key, V value)
{
return new KeyValuePair<K, V>(key, value);
}
}
So short becomes shorter:
var keyValuePair = KeyValuePair.Create(1, 2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With