bradygaster.com

fewer resources, less time, more features

Dictionary Extension Method - Append

December 17 2008
Posted to: ,

I've been creating a few extension methods here and there recently and figured I'd share one of the ones I'm using in a lot of places. This one is an extension method named Append that you can use with a generic IDictionary implementor to do quick-and-dirty creations of the object. I've found this to be really useful when I'm writing tests that use the generic IDictionary class in my tests. The first block of code below will point out the extension method.

 

public static class DictionaryExtensions
{
  public static IDictionary<TKey, TValue> Append<TKey, TValue>(this IDictionary<TKey,TValue> dictionary,
    TKey key, TValue value)
  {
    dictionary.Add(key, value);
    return dictionary;
  }
}

 

This second block demonstrates one potential use for it. In this case I was creating a generic Dictionary to store name/value pairs of data for an HTTP post. 

 

IDictionary<string, string> prms = new Dictionary<string, string>().Append("status", status);

 

Happy coding!

Comments Email Permalink Bookmark and Share kick it

Comments

3/13/2009 8:00:56 AM #

Maik Roempagel

Just what I've been looking for, actually helped me solve two problems at the same time. Much appreciated, keep up the good work!

Maik Roempagel

4/21/2009 9:33:16 PM #

Dave Newman

Object initialiser helps here too:
var prms = new Dictionary<string, string> {{"a", "1"}, {"b", "1"}};

Dave Newman