Geeks With Blogs
Development In a Tesseract Observations and Developmental Experiences

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;
    }
}

Posted on Friday, October 19, 2007 3:24 PM C# | Back to top


Comments on this post: Extension Methods and Dictionaries

Comments are closed.
Comments have been closed on this topic.
Copyright © Steven Mitcham | Powered by: GeeksWithBlogs.net