Blog Stats
  • Posts - 14
  • Articles - 0
  • Comments - 7
  • Trackbacks - 0

 

Extension Methods and Dictionaries

I have started looking at improvements to the NMock2 code with respect to writing a branch of the code in .NET 3.5.

The availability of extension methods in C# 3.0 have solved a common code issue of mine where I want to use Dictionary.TryGetValue to see if there is a value in a dictionary for a given key and create a default if not.  Which leads to the following code.

public static class ExtensionMethods
{
    public static U SafeGetValue<T,U>(this Dictionary<T,U> dictionary, T key)
      where U:new()
    {
        U value;
        if (!dictionary.TryGetValue(key, out value))
        {
            dictionary[key] = value = new U();
        }
        return value;
    }

    public delegate U NewInstance<U>();

    public static U SafeGetValue<T, U>(this Dictionary<T, U> dictionary, T key, NewInstance<U> newInstance)
    {
        U value;
        if (!dictionary.TryGetValue(key, out value))
        {
            dictionary[key] = value = newInstance();
        }
        return value;
    }
}

Comments have been closed on this topic.
 

 

Copyright © Steven Mitcham