Multiple type parameters
Learn multiple type parameters like <TKey, TValue>.
Multiple type parameters
A generic class can take more than one type parameter. The line class Pair<TKey, TValue> asks for two parameters: a key and a value. By convention the names are TKey and TValue but you can pick any names.
This pattern is ideal for structures that hold key-value pairs. The Dictionary<K, V> class works the same way: one key type, one value type. Multiple parameters add flexibility: a single template supports different type combinations.
Holding a key-value pair
Pair<TKey, TValue> is one of the most basic data structures: it keeps a key and its associated value together. The line new Pair<string, int> { Key = "Age", Value = 25 } produces a name-number pair.
You can use this structure as a small dictionary, an option list or a configuration pair. Dictionary<K, V> is essentially a collection of such pairs. Using Pair alone is the simplest way to understand multi-parameter generic design.
Exercise Define the Pair<TKey, TValue> class
Define a Pair<TKey, TValue> generic class with two properties: public TKey Key { get; set; } and public TValue Value { get; set; }. In Main create a Pair<string, int> instance; set Key = "Age", Value = 25. Print Key and Value with Console.WriteLine.
Show example solution
Write class Pair<TKey, TValue> { public TKey Key { get; set; } public TValue Value { get; set; } }. In Main add var p = new Pair<string, int> { Key = "Age", Value = 25 }; Console.WriteLine(p.Key); Console.WriteLine(p.Value);
Example solution:
using System;
class Pair<TKey, TValue>
{
public TKey Key { get; set; }
public TValue Value { get; set; }
}
class Program
{
static void Main()
{
var p = new Pair<string, int> { Key = "Age", Value = 25 };
Console.WriteLine(p.Key);
Console.WriteLine(p.Value);
}
}
Test yourself
-
How is Pair<TKey, TValue> instantiated?
- new Pair(string, int)
- new Pair<string><int>()
- new (string, int) Pair
- new Pair<string, int>()
Show answer
new Pair<string, int>() — Correct. Types are comma-separated inside one angle bracket pair.
-
The second type parameter
class Pair<TKey, ____> { public TKey Key { get; set; } public TValue Value { get; set; } }Show answer
class Pair<TKey, TValue> { public TKey Key { get; set; } public TValue Value { get; set; } } -
Match each piece to its job
- TKey
- Key type
- TValue
- Value type
- Pair<string, int>
- Concrete pair
- Key
- Key property