They represent 4 method requirements as an extension method:
- It must be declared in a static class.
- It should be static (which is actually always true if the first one is executed)
- It must be publicly available.
- It should have the first parameter marked with
this keyword
Thus, you cannot define an extension method in a non-stationary class.
The functionality of the entire extension method is a kind of syntactic sugar. The following extension method declared in MyClass :
// The following extension methods can be accessed by instances of any // class that is or inherits MyClass. public static class Extension { public static void MethodA(this MyClass myInterface, int i) { Console.WriteLine ("Extension.MethodA(this IMyInterface myInterface, int i)"); } }
can be called in two ways:
var myClassObject = new MyClass(); Extension.MethodA(myClassObject);
or
myClassObject.MethodA();
However, the second one will in any case be converted to the first one by the compiler.
source share