I want to understand how extension method works?Can we define extension methods in non static classes?
*
Why do we put extension methods inside static class?
*
According to MSDN,
**Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.
**
What is the role of this operator here and how does it associates that extension method to that argument?
No, you can't define an extension method on a class that is not static.
The this
is syntactic sugar that allows to call your static extension method on an instance. But at the end of the day, an extension method is nothing more than a static method in a static class.
So basically:
var test = myInstance.MyExtensionMethod();
is the same as
var test = MyExtensionClass.MyExtensionMethod(myInstance);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With