- Home /
Default Null Value for Key Not Found in Dictionary?
Is it possible to set a default null value for a case where a key is not found in a dictionary or array?
KeyNotFoundException: The given key was not present in the dictionary. System.Collections.Generic.Dictionary`2[System.String,System.Int32].get_Item (System.String key)
Answer by Statement · Dec 20, 2011 at 01:24 PM
int result = 0;
dict.TryGetValue("Foo", out result);
or
int result = 0;
if (!dict.TryGetValue("Foo", out result))
result = 42; // Default value if we can't get it.
With extension methods you can write a method that does this for you.. GetOrDefault("Foo"); or something.
hmm... not sure how to use extension methods exactly as there does not seem to be a way to pass the Dictionary as an argument in the method! http://answers.unity3d.com/questions/198749/passing-a-dictionary-as-function-arguments-in-c.html
Your answer
Follow this Question
Related Questions
Comparing two objects properties for the closest 0 Answers
Combine Children Dictionary in place of Hashtable? 2 Answers
Hashtable and ArrayList problem 0 Answers
Load txt file (CSV) into Generic Dictionary Javascript 1 Answer
get int based on 3 ints 0 Answers