Hi,
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?
Hi,
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?
The convention is to prefix type names in generics with a capital T
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.
TKey
is the key's type; TValue
is the value 's type.
i.e.
Dictionary<string, int>
is keyed on a string and returns an int
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)
They are the types of the generic. The capital T means type.
List<int> list;
In this example the T
is an int
.
A dictionary is a key/value store. In Dictionary<TKey,TValue>
TKey is the type of the Key, and TValue is the Type of the Value.
It is recommended that you use a similar naming convention if possible in your own generics when there is nore than one type parameter. Otherwise, we get MyGeneric<Q,R,S,T,U,...>
There is a convention to use T to signify the class which your generic class is based on (e.g. List<T>
). A dictionary however is based on two classes, so they chose to distinguish them with the Key and Value suffix.
They could have chosen anything - elsewhere in other scenarios I have seen T and U used, and other subsequent letters (i.e. V, X etc) if more classes are needed.