Extension methods are awesome, but that dang namespacing…

By | July 12, 2013

I think we can all agree that extension methods are something that many of us have taken quite a shining to. Using them to adapt external dependencies, encapsulate common functionality for a 3rd party, and other conveniences has really helped to clean up my own codebase – I know that much.

The one thing that I do find annoying, though, is the fact that in order to get an extension method to show up in the editor (and be usable, for that matter) is you have to include the namespace in which the method’s located in your ‘using’ directives of your class file. This pains me because not only do I like to keep my ‘using’ directives clean (Remove and Sort on Save anybody?), but also I’m annoyed on more than just a handful of occasions when my code fails to compile, the using directive gets removed, and I have to go add it back again. Resharper helps out by automatically knowing where these are, but without it you’re kind of left typing & retyping, and expanding the Object Browser to find out what namespace the extension lives in, blah blah blah.

On a hunch I tried something out the other day, and it actually worked pretty slick, so I thought I’d pass it along.

Create your extension class in a cs file as you normally would:

public static class DictionaryExtensions
/// <summary>
/// Adds or replaces the given key/value pair within the dictionary
/// </summary>
/// <typeparam name="TKey">Type of the keys in the dictionary</typeparam>
/// <typeparam name="TValue">Type of the values in the dictionary</typeparam>
/// <param name="dict">The dictionary that will have the value added or replaced</param>
/// <param name="key">The key to add to the dictionary if it doesn't exist</param>
/// <param name="value">The value to associated with the found/added key</param>
public static void AddOrReplace<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)
if (dict.ContainsKey(key))
dict[key] = value;
dict.Add(key, value);

But notice what I don’t have specified there. The namespace. what this does is makes this extension class show up in the “global namespace”. The effective result is the second you reference the library I’ve put this class in, you get the extensions – no matter what namespaces you have imported. So now any time I am playing w/ Dictionary<TKey, TValue> and have a reference to my Extensions libarary, I get my new “AddOrReplace” extension. For free. Automatically.