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);
}
}
source to share
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.
source to share
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);
source to share