Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are some HtmlHelper methods implemented as extension methods

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.

like image 225
M4N Avatar asked Dec 04 '25 10:12

M4N


1 Answers

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.

like image 119
Brad Wilson Avatar answered Dec 07 '25 00:12

Brad Wilson