views:

23

answers:

1

I have a dictionary that is like this:

Dictionary<string, object> myDictionary = new Dictionary<string, object>();

When I get data out of it, I am doing it like this:

myDictionary["IndexingValue"]

Most of the time that is working. But I just changed one of the values that it stores to be null. Now when I do that same call (expecting null) I get and exception. When I put it in the debugger it says "Could Not Evaluate Expression".

So I said to my self, "OK, somehow my IndexingValue is not in the dictionary. But I went and looked at myDictionary.entries and sure enough it is there.

What I want to do is something like this:

if (myDictionary["IndexingValue"] != <Could not evaluate expression>)
{
    //do some logic.
}

(IE find some way to know when the expression can not be evaluated with out having to throw an exception.)

Can this be done?

+3  A: 

You can use

if (myDictionary["IndexingValue"] != null)
{
    //do some logic.
}

to check whether the item is null or not. As for the "Could Not Evaluate Expression" it's just a debugger output when it cannot for some reason get the value of the item so as long as the dictionary contains the given key it you will not get such error during runtime. To check if the key is in dictionary you can use ContainsKey method.

Giorgi
+1 beat me to it
Robert Greiner
@Vaccano - that's just debugger. See what you get when you run the application.
Giorgi
What is the real exception you are getting from the program, and what is the full code causing it? "Could not evaluate expression" is an error of the debugger. It's not related to your code error, directly.
Andrew Barber
Bingo! I thought that my error was retrieving the value from the dictionary. It was not (I was calling `.Length != 0` on the null result!). Thanks for the tip about the debugger vs runtime that is what got me to take a second look.
Vaccano