Extension method enables to add new method(s) into a class (type / library) without modifying, recompiling or creating derived type.
Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.
Scenario :
We've a class library 'Calculations' in which we have class 'Airithmatics' that contains method 'Add'.
Now we want to add 2 more methods 'Subtract' & 'Multiply' in this library without updating this library.
Limitation: Any extension method(s) with same signature to method(s) of main library / type will never be called
Steps to implement:
Custom Library Code:
Client Code:
Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.
Scenario :
We've a class library 'Calculations' in which we have class 'Airithmatics' that contains method 'Add'.
Now we want to add 2 more methods 'Subtract' & 'Multiply' in this library without updating this library.
Limitation: Any extension method(s) with same signature to method(s) of main library / type will never be called
Steps to implement:
- Create new library named 'ArithmaticAddons'
- Add reference of main library 'Calculations'
- Create a static class 'ArthAddons' in new library
- Add new methods to this class as static method, you want to create as extension methods. Pass main library 'Airithmatics' in methods
- Add reference of both the libraries 'Calculations', 'ArithmaticAddons' in client code
- Create object of main library 'Airithmatics'
- With the object of main library 'Airithmatics', you can see methods of main library & extension methods
- Extension methods displays with a down arrow
Custom Library Code:
using Calculations; //Main
library contains ‘Add’ function
namespace ArithmaticAddons
{
public static class ArthAddons
{
public static int Subtract(this Airithmatics obj, int num1, int num2)
{
return num1 - num2;
}
public static int Multiply(this Airithmatics obj, int num1, int num2)
{
return num1 * num2;
}
}
}
using Calculations; //Main
library contains ‘Add’ function
using ArithmaticAddons; //Custom
library contains subtract & Multiply extension methods
namespace ExtensionMethods
{
class Program
{
static void Main(string[] args)
{
Airithmatics
obj = new Airithmatics();
Console.WriteLine(obj.Add(20,
215).ToString());
Console.ReadLine();
//Extension method Subtract & Multiply call
Console.WriteLine(obj.Subtract(220,
215).ToString());
Console.WriteLine(obj.Multiply(2, 20).ToString());
Console.ReadLine();
}
}
}
No comments:
Post a Comment