C# – TKey and TValue in a generic dictionary

c++generics

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?

Best Solution

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)