Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top