Thursday, February 19, 2009

Extension methods series: Managing the scope

Ok, now that we know how to use extension methods we can go a bit further than that.

The biggest problem of extension methods is their scope. As soon as you have an extension class in scope all its methods are available. We saw previously how to use basic type and interfaces to reduce the scope. Another way to limit the scope is to use namespaces. You namespace must clearly state what type of extension it contains. Usually extensions will be grouped by cross cutting concerns like Collections, Equality, Reflection, Security, Validation, Threading, … and so on. So somehow your namespace should contain one of those words.

namespace Extensions.Validation
{
    public static class RangeValidation
    {
        public static bool IsInRange<T>(this T source, T minIncl, T maxIncl) 
			where T : IComparable<T>
        {
            return minIncl.CompareTo(source) >= 0 
				&& source.CompareTo(maxIncl) >= 0;
        }
    }
}

You can put all your extension methods in the same assembly but in different namespaces. This will help reduce the amount of extension methods you will see in intellisense.

No comments: