user78711
user78711

Reputation: 23

What's "this" used for?

I read some c# codes and can not understand the "this" key word in the function parameter? Could somebody tell me what it is used for? Thanks.

public static class ControlExtensions
{
    public static void InvokeIfNeeded(this Control ctl,
        Action doit)
    {
        if (ctl.InvokeRequired)
            ctl.Invoke(doit);
        else
            doit();
    }

    public static void InvokeIfNeeded<T>(this Control ctl,
        Action<T> doit, T args)
    {
        if (ctl.InvokeRequired)
            ctl.Invoke(doit, args);
        else
            doit(args);
    }
} 

Upvotes: 2

Views: 469

Answers (7)

Lili
Lili

Reputation: 41

It is used to mark the type of object that the extension method is being added to.

Upvotes: 1

Pat
Pat

Reputation: 5282

the static declaration of the method and the this modifier passed in signifies a Extension method where all Control objects will have these methods added on as if they were initially built that way.

i.e: now you can do

Control myControl = new Control();

myControl.InvokeIfNeeded(myaction);

or

myControl.InvokeIfNeeded(myaction, args);

Upvotes: 1

JaredPar
JaredPar

Reputation: 754585

The this modifier in a method declaration signifies that the method is an extension method.

Upvotes: 0

Justin Niessner
Justin Niessner

Reputation: 245399

Adding the 'this' keyword to a parameter like this will cause the method to be interpretted as an Extension method rather than a regular static method.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

It is used to define an extension method for a given type.

Upvotes: 2

Agent_9191
Agent_9191

Reputation: 7253

It signifies an extension method. In the example you gave, any Control object will have the method InvokeIfNeeded(Action doit) available to use. This is in addition to all the methods that a Control already has.

Upvotes: 3

Anton Gogolev
Anton Gogolev

Reputation: 115721

It's used to specify a type on which the extension method operates. That is, public static void InvokeIfNeeded(this Control ctl, Action doit) "adds" an InvokeIfNeeded method to Control class (and all derived classes). This method, however, can only be used if you explicitly import the namespace of a class they are declared in into your scope.

Upvotes: 18

Related Questions