Is it ok to write my own extension methods in the system namespace?

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?

Answers


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.Extensions namespace or a Company.Collections or even a Company.Collections.Extension namespace.

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.


Need Your Help

Spring MVC - RestTemplate launch exception when http 404 happens

spring rest resttemplate

I have a rest service which send an 404 error when the resources is not found.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.