I’ve been using extension methods quite a bit recently and have found a lot of uses for them. The only problem I have is remembering where they are and what namespace to use in order to get the extension methods.
However, I recently had a thought of writing the extension methods in the System namespace, System.Collections namespace or some other system namespace that makes sense. So for example, I’ve implemented the following.
namespace System { /// <summary>Various array extensions</summary> public static class ArrayExtensions { /// <summary>Converts the array to a hex string</summary> /// <param name='value'>The value.</param> /// <returns>The array as a hex string</returns> public static string ToHexString(this byte[] value) { var hex = new StringBuilder(value.Length * 2); foreach (byte b in value) { hex.AppendFormat('{0:X2}', b); } return hex.ToString(); } } }
Is this the correct thing to do?
From the Framework Design Guidelines (2nd Edition):
DO NOT put extension methods in the same namespace as the extended type, unless it is for adding methods to interfaces, or for dependency management.
While this doesn’t explicitly cover your scenario, you should generally avoid extending a Framework namespace (or any namespace you have no control over) and opt instead to put those extensions in their own namespace. If you feel strongly about ‘grouping’ the extensions (such that the collection extensions are together, etc.) then you could introduce a subnamespace. In your scenario, extension to the collections would go in a
System.Collection.Extensionsnamespace or aCompany.Collectionsor even aCompany.Collections.Extensionnamespace.In order to use extension methods the namespace containing the sponsor class (the class that defines the extension methods) must be imported. If you add extension methods to one of the standard .NET Framework namespaces they will always (and implicitly) be available.