What is TKey and TValue in a generic dictionary?

18,743

Solution 1

It is convention to use T for generic types (comparable with "templates" in C++ etc).

If there is a single type (List<T>) then just T is fine (there is nothing more to explain); but if there are multiple generic types, the T prefixes the purpose. Hence TKey is the generic type of the "key", and TValue of the value. If helps in this case if you know that a dictionary maps keys to values!

The intellisense will usually tell you what each type-argument means; for example with Func<T1,T2,TResult>:

  • T1: The type of the first parameter of the method that this delegate encapsulates.
  • T2: The type of the second parameter of the method that this delegate encapsulates.
  • TResult: The type of the return value of the method that this delegate encapsulates.

(taken from the type's comment data)

Solution 2

The convention is to prefix type names in generics with a capital T

Generics best practices

Solution 3

When you create a generic class, you can give any name that you want to a generic type. The convention is to prefix it with "T".

The pattern that I often see is that when you have only one generic type, it is called "T", but when you have more than one, they have explicit names (like TKey and TValue) to differenciate between the different types.

Solution 4

TKey is the key's type; TValue is the value 's type.

eg

Dictionary<string, int> is keyed on a string and returns an int

Share:
18,743
Blankman
Author by

Blankman

... .. . blank

Updated on June 14, 2022

Comments

  • Blankman
    Blankman about 2 years

    The names TKey and TValue in a dictionary are confusing me. Are they named with that convention for a reason or could they have named it anything?

    i.e. if I create a generic, do I have to use some sort of naming convention also?