tags:

views:

589

answers:

6

I tried checking for null but the compiler warns that this condition will never occur. What should I be looking for?

+3  A: 

If you're just checking before trying to add a new value, use the ContainsKey method:

if (!openWith.ContainsKey("ht"))
{
    openWith.Add("ht", "hypertrm.exe");
}

If you're checking that the value exists, use the TryGetValue method as described in Jon Skeet's answer.

ChrisF
TryGet is better
Ruben Bartelink
Coz you're resolving the key lookup through the hashtable twice if you immediately Get after the Contains. Wintellect PowerCollections also has `GetValueElseAdd` methods which you give a value (or a `Func<TValue>`) to also save the resolution on the Insert if you're going to add if its not there. I guess the reason that hasnt made it into the .NET libs is because the Add path is less frequent if you're using it in a cache stylee]
Ruben Bartelink
@rub: I guess that depends on the purpose of the code. If you want to use the value I agree that `TryGetValue` would be better, but if you want to check if the dictionary contains the key in order to avoid duplicate additions, I would say `ContainsKey` is just as good (if not better).
Fredrik Mörk
@Fredrik: If you *only* want to do a containment check, then yes, it's worth using ContainsKey. Note that that's not the case in the sample code of this answer.
Jon Skeet
@Jon: true, I actually missed that the added value was fetched immediately after it was added.
Fredrik Mörk
@Mork: You're right and I agree. Reason I commented is that the post doesnt make it clear that you generally want to do either ContainsKey (only) OR TryGet (Contains + Get) OR TryGet / Add (without another Get like in the code sample in the post)
Ruben Bartelink
@Jon - I've removed the inefficient code and clarified my answer a bit.
ChrisF
@Ruben - I've updated the code now. Should be a bit clearer now
ChrisF
+1'd. Will move my comments to a new question post shortly
Ruben Bartelink
The comments here got me to ask a question I'd long wanted to ask:- http://stackoverflow.com/questions/2139423/what-is-the-bcl-equivalent-of-getvalueelseadd-in-powercollections I guess I'll leave my comment spam here for posterity
Ruben Bartelink
A: 

You should check for Dictionary.ContainsKey(int key) before trying to pull out the value.

Dictionary<int, int> myDictionary = new Dictionary<int, int>();
myDictionary.Add(2,4);
myDictionary.Add(3,5);

int keyToFind = 7;
if(myDictionary.ContainsKey(keyToFind))
{
    myValueLookup = myDictionay[keyToFind];
    // do work...
}
else
{
    // the key doesn't exist.
}
ZombieSheep
Why do you want to make it do the lookup twice?
Jon Skeet
@Jon because it usually reads better
mookid8000
@mookid: Not in my opinion. The idea is to try to look up the key, and take one course of action if it's found, and another course of action otherwise, right?
Jon Skeet
@Jon - Honestly? Because I didn't know about `TryGetValue`. Thankfully, I do now, so I'll know in future. I'm going to leave this answer intact, though 'cos discussion is valuable.
ZombieSheep
@ZombieSheep: Fair enough. Isn't SO great for learning? :)
Jon Skeet
@Jon Skeet - It's why I'm here. :)
ZombieSheep
A: 

ContainsKey is what you're looking for.

Will
A: 

You should probably use:

if(myDictionary.ContainsKey(someInt))
{
  // do something
}

The reason why you can't check for null is that the key here is a value type.

Razzie
The type of the value is somewhat irrelevant, as checking for null wouldn't have the desired effect.
Jon Skeet
@Johannes, Jon's solution is of course way better, but the asker did state that he checked if the key exists, and it is a Dictionary<int, int>, so the key is also a value type here.
Razzie
+16  A: 

Assuming you want to get the value if the key does exist, use Dictionary<TKey, TValue>.TryGetValue:

int value;
if (dictionary.TryGetValue(key, out value))
{
    // Key was in dictionary; "value" contains corresponding value
} 
else 
{
    // Key wasn't in dictionary; "value" is now 0
}

(Using ContainsKey and then the the indexer makes it look the key up twice, which is pretty pointless.)

Note that even if you were using reference types, checking for null wouldn't work - the indexer for Dictionary<,> will throw an exception if you request a missing key, rather than returning null. (This is a big difference between Dictionary<,> and Hashtable.)

Jon Skeet
Apologies, I momentarily had an out/ref mixup. Comment withdrawn.
Richard Szalay
Reply to comment withdrawn too :)
Jon Skeet
A: 

The Dictionary throws a KeyNotFound exception in the event that the dictionary does not contain your key.

As suggested, ContainsKey is the appropriate precaution. TryGetValue is also effective.

This allows the dictionary to store a value of null more effectively. Without it behaving this way, checking for a null result from the [] operator would indicate either a null value OR the non-existance of the input key which is no good.

antik
Additional information can be found at MSDN:http://msdn.microsoft.com/en-gb/library/9tee9ht2.aspx
cyberzed