C# Programming > Data

C# KeyValuePair

 

C# KeyValuePair

Many C# variable types hold a single value. But how to store a pair of related values? That's where C# KeyValuePair structure comes in. The KeyValuePair structure (not class) is a generic structure that lets programmers work with two values at once.

Notice that it is mostly for convinience because there is nothing stopping you from writing your own C# struct to hold two or more values. KeyValuePair simply makes things faster.

Generic KeyValuePair

The C# KeyValuePair is generic, which means that the programmer can specify what type of data it will hold. So for example, if you want to store key/value pairs of strings and integers, you can define a KeyValuePair as:

KeyValuePair<string, int> keyValue = new KeyValuePair<string, int>("string", 1);

The key and values can then be accessed through the Key and Value property respectively. There is one downside. Notice that the values of the KeyValuePair must be assigned when a new instance is created. The Key and Value properties are read-only so you cannot modify their values.

C# KeyValuePair types do not have many more methods. It can be noted that the ToString function was nicely implement to display both values in a [key, value] format.

Finally it is important to remember that a KeyValuePair is a structure NOT a class. There are some differences such as where the object is stored in memory (in the stack in this case) and the fact that it does not work based on references.

Back to C# Article List