Reputation: 5414
I've searched a bit, but I can't seem to find any information on the TKey and TValue parameters of the Dictionary class..
Is TKey just a value you specify to make a TValue unique?
Is TValue just a value of your own decision that doesn't have any impact on the search of the Dictionary class?
Upvotes: 3
Views: 304
Reputation: 612993
A dictionary is also known as an associative array, or a map.
It is a generic container just like List(T)
and it contains items of type TValue
. You can thus use the generic type TValue
to determine the type of each element.
The key is what you use to index each item. The difference between a dictionary and a list or array is that the index for a dictionary is not restricted to being an integer. It also does not need to be contiguous. Thus the type you specify for TKey
does not need to be an integer. Very often string
is used.
This allows you to write something like:
Dictionary<string, int> Reputation = new Dictionary<string, int>();
Reputation["Jon Skeet"] = 360737;//and counting
If you then need to retrieve this value you can write:
int rep = Reputation["Jon Skeet"];//rep now contains the value 360737
If someone upvotes then you can write:
Reputation["Jon Skeet"] += 10;
and so on.
Upvotes: 0
Reputation: 956
Did you try here http://msdn.microsoft.com/en-us/library/xfhwa508.aspx
Scroll down to remarks.
Upvotes: 1
Reputation: 12458
A dictionary stores a Key-Value-Pair. You can take anything for to be the value and the key. You decide it, when you create such a dictionary. E.g.:
Dictionary<int, string> myDictionary = new Dictionary<int, string>();
With that you get a dictionary taking a string for to be a value and an integer for its key. It depends on what you need!
Upvotes: 0
Reputation: 10411
You're correct on both counts. The key is a unique value of the type you specify when you create a dictionary, and the value is any valid value for the value type you define when you create the dictionary.
Upvotes: 1
Reputation: 1500785
A dictionary is a mapping of keys to values.
TKey
is the type of the key. TValue
is the type of the value.
So for example, if I were mapping string
to Person
(because I had a collection of people and I wished to be able to find one by name quickly) I'd use a
Dictionary<string, Person>
Note that the key doesn't make the value unique. There can be two keys which use the same value. However, each key is only associated with one value.
Upvotes: 4
Reputation: 300559
Yes
Yes.
Parameters prefixed with 'T' are just placeholders for a Type.
Upvotes: 0