IDictionary .Contains and .ContainsKey
21 March 2010
I have already discussed the Hashtable class which is a built-in .NET class (in mscorlib.dll) which implements the IDictionary interface. In this previous example I used the containsKey method to look up the value for a key.
If you are going to build your own class which implements IDictionary then you will need to implement Contains method to see if key values are in the dictionary
1) Implement IDictionary.Contains Method
Determines whether the IDictionary object contains an element with the specified key.
The following code example demonstrates how to implement the Contains method. This code example is part of a larger example provided for the IDictionary class:
public bool Contains(object key)
{
Int32 index;
return TryGetIndexOfKey(key, out index);
}
Source: Microsoft
2) Example call to IDictionary(TKey, TValue).ContainsKey Method
Determines whether the IDictionary(TKey, TValue) contains an element with the specified key.
The following code example shows how to use the ContainsKey method to test whether a key exists prior to calling the Add method:
if (!openWith.ContainsKey("ht"))
{
openWith.Add("ht", "hypertrm.exe");
Console.WriteLine("Value added for key = \"ht\": {0}",
openWith["ht"]);
}
Source: Microsoft
As you can see in Nick Guerrera’s blog, implementing IDictionary(TKey, TValue) isn’t trival.
If you liked this blog post, you may want to subscribe to my news feed in your RSS reader.
