When i do val = dict["nonexistent key"] i get System.Collections.Generic.KeyNotFoundException Is there a way i have my dictionary call a member function with the key as a param to generate a value?
-edit- Maybe i should of been more specific. I want to AUTOMATICALLY call a member function to do what it needs create the proper value for that key. In this case it makes an entry in my DB then gives me back its unique handle. I'll post below what my solution was.
Use an extension method:
static class DictionaryExtensions {
public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey,TValue> dic, TKey key, Func<TKey, TValue> valueGenerator) {
TValue val;
if (dic.TryGetValue(key, out val))
return val;
return valueGenerator(key);
}
}
You can call it with:
dic.GetValueOrDefault("nonexistent key", key => "null");
Or pass a member function:
dic.GetValueOrDefault("nonexistent key", MyMemberFunction);
Object value;
if(dict.TryGetValue("nonexistent key", out value))
{
// this only works when key is found..
}
// no exception is thrown here..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With