Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "this" mean when used as a prefix for method parameters?

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?

like image 889
Scott Anderson Avatar asked Jun 09 '09 20:06

Scott Anderson


3 Answers

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.

like image 36
C. Ross Avatar answered Nov 14 '22 11:11

C. Ross


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).

like image 128
tanascius Avatar answered Nov 14 '22 10:11

tanascius


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.

like image 1
J.W. Avatar answered Nov 14 '22 10:11

J.W.