My code has the following in an Action Method:
catch (Exception e)
{
log(e);
return Content(ExceptionExtensions.GetFormattedErrorMessage(e));
}
The function called looks like this:
public static class ExceptionExtensions
{
public static string GetFormattedErrorMessage(this Exception e)
if (e == null)
{
throw new ArgumentNullException("e");
}
Can someone explain why there is a “this” at the start of the parameter list?
This is the signature of the extension methods. They were introduced in .NET3.5(C#3). Without
thisthe compiler would take it as a static method signature.in the following code:
You can call the static method like this:
and the extension method like this:
and the extension method as a static method:
So, to convert an extension method to static method all you have to do is remove the
thiskeyword from the signature.However, if you want to convert a static method into an extension methods you have to:
thiskeyword to the signaturepublic staticclasspublicScott Hanselman has a good article on the choice of the syntax and how it fit the existing CLR with minimal changes to the compiler.
In summary, he concludes that after compilation, there is no difference between the generated IL code for a static method and the code for an extension method.
The
thiskeyword is there to instruct the compiler to put some meta data around the extension method.My guess is that they have gone for the
thiskeyword because 1.it already existed and 2. its existing meaning best fitted in the context of the extension method compared to the other existing keywords.