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.
An Extension Method should be in the same namespace as it is used or you need to import the namespace of the class by a using statement. You can give any name of for the class that has an Extension Method but the class should be static.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
To define and call the extension methodDefine a static class to contain the extension method. The class must be visible to client code. For more information about accessibility rules, see Access Modifiers. Implement the extension method as a static method with at least the same visibility as the containing class.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With