Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group extension methods?

I have a static class with bunch of extension methods for various types. Is there any utility or the way to split it into several classes - separate class for the each target type.

like image 247
Peter17 Avatar asked Mar 02 '11 14:03

Peter17


2 Answers

Putting your various extension methods into different classes is a good idea from a "clean code" perspective, but the main "grouping" of extension methods happens by placing them into different namespaces. The reason is that extension methods are made available by "using" the appropriate namespace.

Putting different groups of extension methods into different namespaces is a good idea since you could have colliding extension methods. If that happens, and each logical group of extension methods is in a fine-grained namespace, you should be able to resolve the conflict by simply removing one of the using statements, thereby leaving the using statement that contains the extension method you actually want.

Here's a link to some best practices:

http://blogs.msdn.com/b/vbteam/archive/2007/03/10/extension-methods-best-practices-extension-methods-part-6.aspx

like image 182
Adam Rackis Avatar answered Sep 24 '22 18:09

Adam Rackis


I have another way of grouping:

public class StringComplexManager
{
    public StringComplexManager(String value)
    {
        Value = value;
    }

    public String Value { get; set; }
}

public static class StringComplexExtensions
{
    public static StringComplexManager ComplexOperations(this String value)
    {
        return new StringComplexManager(value);
    }

    public static int GetDoubleLength(this StringComplexManager stringComplexManager)
    {
         return stringComplexManager.Value.Length * 2;
    }
}

Usage is:

string a = "Hello"
a.ComplexOperations().GetDoubleLength()

ComplexOperation() groups the extension methods and narrows the intellisense scope so that if you originally had hundreds of string extension methods you now only see one in intellisense.

like image 42
magnusarinell Avatar answered Sep 24 '22 18:09

magnusarinell