Click here to Skip to main content
15,895,709 members
Articles / Programming Languages / C#

Extension methods are awesome, but that dang namespacing…

Rate me:
Please Sign up or sign in to vote.
2.92/5 (7 votes)
3 Oct 2013CPOL2 min read 11.4K   5   13
A useful utility.

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:

C#
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;
        }
        else
        {
            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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
I'm a Sr. Software Engineer in the Seattle area primarily focused on serverless technologies in the cloud. In my free time I enjoy hiking & other adventures with my family around the Puget Sound and the country! You can find out more about me at my homepage: http://bc3.tech/brandonh

Comments and Discussions

 
GeneralMy vote of 2 Pin
Rui Jarimba10-Oct-13 2:51
professionalRui Jarimba10-Oct-13 2:51 
GeneralMy vote of 2 Pin
ke4vtw8-Oct-13 5:26
ke4vtw8-Oct-13 5:26 
SuggestionTip/trick Pin
Qwertie7-Oct-13 12:25
Qwertie7-Oct-13 12:25 
GeneralRe: Tip/trick Pin
BC3Tech7-Oct-13 14:38
BC3Tech7-Oct-13 14:38 
QuestionDangerous idea Pin
Kuzhelev Roman4-Oct-13 22:46
Kuzhelev Roman4-Oct-13 22:46 
As it has been mentioned by William E. Kempf, you could easily face the troubles when you will just try to reference your assembly with declaration of extension methods. That's the case when you will have to spend your time in order to resolve compile time issues. But it is a case when you will not receive any compile time errors and will discover erratic behavior only at runtime. Suppose you have a class Widget that declares an instance method with following signature: void Decorate(). Suppose that you also have an extension method with the same "usage" signature: void Decorate(this Widget). Suppose also that you have placed extension methods in a global namespace. Now consider the following situation. You have used a Decorate() method in your code - and everything will be ok due to compiler could resolve this issue when there are two methods with appropriate signature to call - preference will be given to an instance method implicitly. But after a while you've decided that Decorate() instance method should depend on the specific DecorationRules, and you've changed the signature of instance method to void Decorate(DecorationRules rules). After such kind of changes everyone expects that compile time errors will help him to fix the problem and provide each method with absent DecorationRules argument - but there will be not any kind of such errors. Extension method will be called instead of instance one, and in order to prevent it you should find all the places where Decorate() method is called. And I promise you that if your project will be not the project builded upon three classes or few, you probably will miss some places where changes were expected to be in order to provide appropriate runtime behavior. And in the worst case these bugs will be discovered only by the clients of your code.
GeneralMy vote of 1 Pin
Athari4-Oct-13 1:57
Athari4-Oct-13 1:57 
GeneralThoughts Pin
PIEBALDconsult3-Oct-13 13:41
mvePIEBALDconsult3-Oct-13 13:41 
QuestionNot such a good idea Pin
William E. Kempf3-Oct-13 9:12
William E. Kempf3-Oct-13 9:12 
AnswerRe: Not such a good idea Pin
BC3Tech3-Oct-13 9:18
BC3Tech3-Oct-13 9:18 
GeneralRe: Not such a good idea Pin
William E. Kempf3-Oct-13 9:28
William E. Kempf3-Oct-13 9:28 
GeneralGood idea but ... Pin
Carlos A Alvarez3-Oct-13 5:07
Carlos A Alvarez3-Oct-13 5:07 
GeneralRe: Good idea but ... Pin
BC3Tech3-Oct-13 5:34
BC3Tech3-Oct-13 5:34 
GeneralRe: Good idea but ... Pin
PIEBALDconsult3-Oct-13 13:19
mvePIEBALDconsult3-Oct-13 13:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.