posted 7/20/2010 by Hajan Selmani
Dictionary is an interesting mechanism which provides us very good way to associate keys and values on a simple manner. Key/Values can be of any type.
I won't get into explaining what is (or what is not) a Dictionary, but this blog's focus is about one common mistake that I've seen constantly made by juniors and beginners in C# & ASP.NET.
Let's say we have the following code block:
Dictionary<string, string> dict = new Dictionary<string, string>(); dict.Add("name", "Hajan"); dict.Add("surname", "Selmani"); dict.Add("city", "Skopje"); dict.Add("country", "Macedonia");
This is Dictionary which accepts key of type string and value of type string.There are four keys: name, surname, city, country - each associated with value of type string.
I see that some developers when retrieving any value of the dictionary, they do something like this:
if (dict["country"] != null) { Response.Write(dict["country"]); } else if (dict["state"] != null) { Response.Write(dict["state"]); }
which is totally wrong way!
What if in the future, we remove the dict.Add("country", "Macedonia") key or change the keyName to lets say dict.add("state","Macedonia") ???
If we do that, the code will throw an error:
The given key was not present in the dictionary.
So, the right way to check whether "country" key exists or not is using the ContainsKey method of the Dictionary object.
if (dict.ContainsKey("country")) { Response.Write(dict["country"]); } else if (dict.ContainsKey("state")) { Response.Write(dict["state"]); }
Dictionary class also contains ContainsValue method, if you want to search for values inside dictionary key pairs.
I hope this was useful info for you.
Regards,Hajan
Nice blog Hajan.
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18