views:

129

answers:

3

Do you use a global, catchall namespace for all of your extension methods, or do you put the extension methods in the same namespace as the class(es) they extend?

Or do you use some other method, like an application or library-specific namespace?

I ask because I have a need to extend System.Security.Principal.IIdentity, and putting the extension method in the System.Security.Principal namespace seems to make sense, but I've never seen it done this way.

+5  A: 

I would recommend putting all your extension methods in a single namespace (incidentally this is also what Microsoft did with System.Linq --> System.Linq.Extensions).

Since Visual Studio provides no clues as to how to locate an extension method that you want to use, it reduces confusion by only having to remember one namespace.

Andrew Hare
That makes sense with `System.Linq`, since all of those extension methods are conceptually related to `System.Linq`.
Robert Harvey
So by your reckoning, putting my extensions in `System.Security.Principal.Extensions` makes sense also?
Robert Harvey
+3  A: 

If they're extension methods used throughout the solution (e.g. over 60% of classes), I put them in the base namespace of the solution (since they'll be automatically imported being in a parent namespace, no importing the common stuff every time).

In this category, things like:
.IsNullOrEmpty(this string value) and .HasValue(this string value)

However, if they're very specific and rarely used, I put them in a BaseNamepace.Extensions namespace so they must be manually imported and don't show in intellisense cluttering things up everywhere.

Nick Craver
+1  A: 

Put your extensions in the same namespace as the classes they extend. That way, when you use the class, the extensions are available to you.

  • If you are writing a extension for Uri, put the extension in System.
  • If it's a extension for DataSet, put it in System.Data.

Also, Microsoft says this about extension methods:

In general, we recommend that you implement extension methods sparingly and only when you have to. Whenever possible, client code that must extend an existing type should do so by creating a new type derived from the existing type.

For more info about extension methods, see the MSDN page about extension methods.