views:

366

answers:

5

How do you organize your Extension Methods? Say if I had extensions for the object class and string class I'm tempted to separate these extension methods into classes IE:

public class ObjectExtensions
{
    ...
}

public class StringExtensions
{
    ...
}

am I making this too complicated or does this make sense?

+1  A: 

Tis what i do. I'll put them in their own namespace often as well, if warranted.

Darren Kopp
+1  A: 

That is how I separate my extension methods as well. Makes it easier to find a given extension method.

Abe Heidebrecht
+1  A: 

I like that approach because it makes discovery of the classes that implement extension methods very straightforward aiding maintenance.

smink
+3  A: 

There are two ways that I organize the extension methods which I use,

1) If the extension is specific to the project I am working on, then I keep it in the same project/assembly, but in its own namespace.

2) If the extension is of a kind so that I may or is using it in other projects too, then I separate them in a common assembly for extensions.

The most important thing to keep in mind is, what is the scope which I will be using these in? Organizing them isn't hard if I just keep this in mind.

Geir-Tore Lindsve
+9  A: 

I organize extension methods using a combination of namespace and class name, and it's similar to the way you describe in the question.

Generally I have some sort of "primary assembly" in my solution that provides the majority of the shared functionality (like extension methods). We'll call this assembly "Framework" for the sake of discussion.

Within the Framework assembly, I try to mimic the namespaces of the things for which I have extension methods. For example, if I'm extending System.Web.HttpApplication, I'd have a "Framework.Web" namespace. Classes like "String" and "Object," being in the "System" namespace, translate to the root "Framework" namespace in that assembly.

Finally, naming goes along the lines you've specified in the question - the type name with "Extensions" as a suffix. This yields a class hierarchy like this:

  • Framework (namespace)
    • Framework.ObjectExtensions (class)
    • Framework.StringExtensions (class)
    • Framework.Web (namespace)
      • Framework.Web.HttpApplicationExtensions (class)

The benefit is that, from a maintenance perspective, it's really easy later to go find the extension methods for a given type.

Travis Illig
Wow, good thing I ran into this answer before creating my first extension class.
Sung Meister