views:

236

answers:

3

I'm currently creating some custom helper classes, similar to ASP.NET MVC's standard HtmlHelper. When I looked at the implementation of HtmlHelper, I noticed that most/all of the HTML generating methods (such as ActionLink(), BeginForm(), TextBox(), and so on) are not implemented directly inside the HtmlHelper class, but as extension methods in separate classes (e.g. in class LinkExtensions).

Apart from a nicer source-code organisation, is there any advantage when implementing such methods as extension methods instead of normal methods?

When creating my own helper classes, should I also follow that pattern?

Update: when I wrote that I wanted to create my own helper class, then I did mean to extend the existing HtmlHelper class. Instead I created a custom base class for my views (derived from ViewPage) and I want to add there an additional helper class similar to the Html and Url helper classes of ViewPage.

A: 

I tend to follow that pattern by having core classes, and then extension classes for each one where needed.

Regarding advantages... I'm not aware of anything apart from separating the actual classes themselves from their extensions.

Dan Atkinson
+3  A: 

I suppose it might be because the Framework Design Guidelines mentions (4.1):

Avoid having types designed for advanced scenarios in the same namespace as types intended for common programming tasks.

and later on (5.6) about extension methods:

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.

Phil Haack himself mentions on the same page that they put "more advanced" funcionality in a separate namespace in order not to "pollute" the API of the extended type.

I agree that the methods that actually are more useful (ActionLink and so on) are less discoverable, but they are all implemented using the core API of HtmlHelper (GenerateLink, etc.) which is part of the main namespace.

If you intend to follow the official design guidelines and it makes sense in your specific case, I think you should adhere to this pattern.

Lck
ISBN-10: 0321545613ISBN-13: 978-0321545619
Dan Atkinson
+3  A: 

The reason is: we wanted to provide you with the ability to opt-out to any of the built-in HTML helpers in case you preferred to write your own or use some other 3rd party helpers instead. If they weren't extension methods in a special namespace, you wouldn't be able to ignore them.

Brad Wilson
So it's not needed to build my own helper classes in the same way?
M4N
Actually, extension methods are the only way you can write HTML helpers.
Brad Wilson
I don't want to extend HtmlHelper! I have updated the question with some more details.
M4N