What is "this" used for?

I've read some C # codes and can't figure out the "this" keyword in a function parameter? Can anyone tell me what it is used for? Thank you.

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);
    }
} 

      

+2


source to share


7 replies


It used to indicate the type on which the extension method works. That is, it public static void InvokeIfNeeded(this Control ctl, Action doit)

"adds" the method InvokeIfNeeded

to the class Control

(and all derived classes). However, this method can only be used if you explicitly import the class namespace in which they are declared in your scope.



+18


source


This means extension method. In the example you provided, any Control object will have an InvokeIfNeeded (Action doit) method available for use. This is in addition to all the methods the control already has.



+3


source


Used to define an extension method for a given type.

+2


source


a static method declaration and passed this modifier means an extension method in which all Control objects will have these methods added as if they were originally constructed this way.

that is: now you can do

Control myControl = new Control();

myControl.InvokeIfNeeded(myaction);

      

or

myControl.InvokeIfNeeded(myaction, args);

      

+1


source


Used to denote the type of object to which the extension method is added.

+1


source


Adding the keyword 'this' to a parameter like this will cause the method to be interpreted as an extension method rather than a normal static method.

0


source


This modifier in a method declaration indicates that the method is an extension method.

0


source







All Articles