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 and 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
public static void AddOrReplace<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)
dict[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.