.net – C# dictionary<> missing key – Education Career Blog

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..

,

Just as an aside, the technique you’re talking about is called Memoization

,

TryGetValue() is good. You can also use ContainsKey() if you aren’t performance constrained or don’t need the value.

,

if(myDictionary.ContainsKey("TestKey") 
{       
  System.Print(myDictionary"TestKey"); 
}

,

    string Q = "nonexistent key";
    string A = "";


    if(dict.containskey(Q))
    {
        A= dictQ;
    }
    else
    {
       //handler code here
    }

,

public class MyDictionary<K, V>
{
    Dictionary<K, V> o = new Dictionary<K, V>();
    public delegate V NonExistentKey(K k);
    NonExistentKey nonExistentKey;
    public MyDictionary(NonExistentKey nonExistentKey_)
    {   o = new Dictionary<K, V>();
        nonExistentKey = nonExistentKey_;
    }

    public V thisK k
    {
        get {
            V v;
            if (!o.TryGetValue(k, out v))
            {
                v = nonExistentKey(k);
                ok = v;
            }
            return v;
        }
        set {ok = value;}
    }

}

Leave a Comment