Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does extension method works [duplicate]

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?

like image 481
F11 Avatar asked Dec 15 '22 11:12

F11


1 Answers

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);
like image 75
ken2k Avatar answered Dec 26 '22 11:12

ken2k