Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
How Do We Create Extension Methods?
Step 1: Create the Static Class
Step 2: Create the Static Method and give any logical name to it.
Step 3: In the Extension Method Parameter, just pass this along with the object type.
Implementation :
If we have a third party class (Important), which is not accessible to developer named "Class1".
and you want to create an extension method to that class ( for example a method that return "This is extended method") then, according to our steps :
Create a static class :
public static class Extension{}
Step 2 & 3:
We need an extension method to mark the function as
static
(so that it can be accessed at any time without the need for declaring anything) and secondly, mark the first parameter with the this
keyword. This keyword basically tells the CLR that when this extension method is called, to use "this
" parameter as the source. public static class Extension{
public static string ReturnString(this ClassNeedToBeExtended classObj)
{
return "is used to call the extended method";
}
}
How to use Extended Method?
Its quite same like using the normal methods of the class, just make an object of the class and now you will have access to our extended method too.
ClassNeedToBeExtended class1 = new ClassNeedToBeExtended();
class1.ReturnString();
Point to be considered :
Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.
Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.
If you create an extension method with the same name as another method in that type, the compiler will bind the method call to the native method, not any extension. An extension method is only called when there is no native method found.
No comments:
Post a Comment