0

Can an extension method be a non static method? Why is it mandatory for an extension method to be defined as a static method of a static class?

Cid
  • 14,968
  • 4
  • 30
  • 45
Atom99
  • 29
  • 7
  • 1
    Could be because that's how the language was designed. – Cid Feb 26 '20 at 08:39
  • 4
    And from [docs](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods) : *"the intermediate language (IL) generated by the compiler translates your code into a call on the static method. Therefore, the principle of encapsulation is not really being violated."* – Cid Feb 26 '20 at 08:40
  • 1
    How, could this even work if they were not static? If you could do `public class A { public void ExtensionMethod(this B b) { } }` and you do `b.ExtensionMethod();` how would it know which instance of A to use? – ckuri Feb 26 '20 at 08:48
  • @ckuri i do not understand, can you elaborate it? Doesn't the "this" keyword bind the class B to A? why do i need to have a static method for that? – Atom99 Feb 26 '20 at 09:15
  • 1
    Does this answer your question? [Extension methods require declaring class to be static](https://stackoverflow.com/questions/2731695/extension-methods-require-declaring-class-to-be-static) – Selim Yildiz Feb 26 '20 at 09:21
  • 1
    The `this` keyword in this context is just a marker for an extension method. C# extension methods are defined via `static class A { public static void ExtensionMethod(this B b) { } }` and `this` does not refer to A (and it couldn't anyway as A is a static class and there is never a `this` to refer to) but to B as you extend B. `this` here has the notion that you are pretending as if ExtensionMethod were defined in B and the `b` argument of the method would be `this`. But then again if they were not static which instance of A should it take and what if ExtensionMethod would access fields of A? – ckuri Feb 26 '20 at 09:26

0 Answers0