Tip: how to simplify value access from a dictionary ? With an extension method !

I was getting really bored with testing .ContainsKey() at each time I wanted to read a value from a dictionary.

Dictionary<string, string> dico; if (dico.ContainsKey("key")) value = dico["key"]; else value = "default";

A incredibly simple extension method solves this so easily:

public static class MyExtensions { public static TValue GetValue<TKey, TValue>( this IDictionary<TKey, TValue> source, TKey key, TValue defaultValue) { if (source.ContainsKey(key)) return source[key]; else return defaultValue; } }

The call from any dictionary now becomes:

value = dico.GetValue("key", "default");

…sometimes I just wonder how I did not think about such solutions earlier ! 🙂

Comments (6)

  1. Ian says:

    You can optimise this slightly further by using TryGetValue… 🙂

  2. Steve says:

    public static class MyExtensions


       public static TValue GetValue<TKey, TValue>(

           this IDictionary<TKey, TValue> source,

           TKey key, TValue defaultValue)


           TValue result;

           return source.TryGetValue(key, out result) ? result : defaultValue;



  3. Funy Mitsu ! I do the same for Request Params.

  4. Mitsu Furuta says:

    Thanks for the TryGetValue modification. It is much better using it.

    The extension method still brings an easier syntax, allowing to be used inside an expression.

  5. Sandy Place says:

    Yet another variation.

    public static TValue        GetValue<TKey, TValue>(this IDictionary<TKey, TValue> source, TKey key)


      TValue result;

      return source.TryGetValue(key, out result) ? result : default(TValue);