Dictionary<string, string>

J

Jonathan Wood

I'm trying to implement code that uses Dictionary<string, string>.

I got the basics working very quickly, although it took me about an hour to
figure out how to make the comparision case-insensitive.

Now, I'm having trouble because this collection raises an exception rather
than returning null if the specified key is not in the dictionary. I can
use ContainsKey but then I'd have to do another lookup if ContainsKey
returns true. Otherwise, I have to implement another exception handler.
Neither options seems like the most efficient approach to such a simple
task.

Is there any method to get a Dictionary<string, string> value that only
requires a single lookup but intelligently handles keys that are not in the
collection? My preference would be something like this:

var x = dict["key"];
if (x != null)
...

Thanks.
 
J

Jonathan Wood

General suggestion: when looking for features in a specific .NET class,
look at the "Class Members" page for the class, on MSDN. You will often
find what you're looking for there.

I appreciate that but I use "Class Members" all the time. I just wasn't
seeing anything helpful in this case.
For your particular question, you want to use the TryGetValue() method.
The docs will explain how to use it.

That'll work. Cool.
By the way, note that there's a very good reason "null" is not returned
when the key isn't present: "null" is a perfectly valid value to use for a
key, at least when TValue is a nullable type (i.e. reference type or
nullable value type). There would be no way to tell the difference
between a missing key and an existing key with value "null".

I appreciate the complete answer, thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top