views:

91

answers:

2

I'm following a tutorial on MVC on the .NET 4 framework. The tutorial created a function like this...

using System.Web;
using System.Web.Mvc;

namespace vohministries.Helpers
{
    public static class HtmlHelpers
    {
        public static string Truncate(this HtmlHelper helper, string input, int length)
        {
            if (input.Length <= length)
            {
                return input;
            }
            else
            {
                return input.Substring(0, length) + "...";
            }
        }
    }
}

I have no idea whatthis HtmlHelper helper means or represents in the function argument. Is this something new in .NET 4? I think it may be extending the HtmlHelper class but I'm not sure...Could someone explain the syntax?

+6  A: 

It's an extension method. (Been in since C# 3.0):

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

Mitch Wheat
This is mostly bang-on, but they're a 3.5 feature ;)
Bennor McCarthy
Ooops! Thx. Could have sworn I'd used them in 2.0 !
Mitch Wheat
A: 

You can call that extension method in two ways:

HtmlHelpers.Truncate(helper, input, length)

OR

helper.Truncate(input, length)
Carlos Muñoz