views:

289

answers:

5

I'm sure the answer is something obvious, and I'm kind of embarrassed that I don't really know the answer already, but consider the following code sample I picked up while reading "Professional ASP.NET MVC 1.0":

public static class ControllerHelpers
{
    public static void AddRuleViolations(this ModelStateDictionary modelState, IEnumerable<RuleViolation> errors)
    {
        foreach (RuleViolation issue in errors)
            modelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
    }
}

I understand what this static method is doing, but what I don't understand is what purpose the word "this" is serving in the method signature. Can anyone enlighten me?

+16  A: 

That is a new C# 3.0 feature called extension method.

It means, that you add a new method to your ModelStateDictionary objects. You can call it like a normal method:

yourModelStateDictionary.AddRuleViolations( errors );

See, that the first parameter (the 'this'-parameter) is skipped. It assigns just ModelStateDictionary as a valid target for your extension method.

The clue is, that you can do this with any class - even sealed or 3rd party classes, like .Net framework classes (for instance on object or string).

tanascius
Couldn't have put it better my self
TWith2Sugars
+1  A: 

It means the method in question is an "extension method" and can be called as if it was a method of the class itself. See this article.

C. Ross
A: 

Also see here: Extension Methods (C# Programming Guid)

Dave Van den Eynde
+1  A: 

It is an extention method signature, It means the "AddRuleViolations" will be treated as an extention method of ModelStateDictionary.

From MSDN.

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.

J.W.
A: 

It adds an extension method to all instances of ModelStateDictionary.

PatrikAkerstrand