What does 'this' keyword mean in a method parameter?

InGeek picture InGeek · Feb 23, 2013 · Viewed 12.8k times · Source
namespace System.Web.Mvc.Html
{
    // Summary:
    //     Represents support for HTML in an application.
    public static class FormExtensions
    {
        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName);
...
    }
}

I have noticed that 'this' object in front of the first parameter in BeginForm method doesn't seem to be accepted as a parameter. Looks like in real BeginForm methods functions as:

BeginForm(string actionName, string controllerName);

omitting the first parameter. But it actually receives that first parameter somehow in a hidden way. Can you please explain me how this structure works. I actually exploring MVC 4 internet Sample. Thank you.

Answer

Yair Nevet picture Yair Nevet · Feb 23, 2013

This is how extension methods works in C#. The Extension Methods feature allowing you to extend existing types with custom methods. The this [TypeName] keyword in the context of method's parameters is the type that you want to extend with your custom methods, the this is used as a prefix, in your case, HtmlHelper is the type to extend and BeginForm is the method which should extend it.

Take a look at this simple extention method for the string type:

public static bool BiggerThan(this string theString, int minChars)
{
  return (theString.Length > minChars);
}

You can easily use it on string object:

var isBigger = "my string is bigger than 20 chars?".BiggerThan(20);

References: