We have improved our answer with detail explanation.Now it's more easy to understand about extension method
Extension method: It is a mechanism through which we can extend the behavior of existing class without using the sub classing or modifying or recompiling the original class or struct.
We can extend our custom classes ,.net framework classes etc.
Extension method is actually a special kind of static method that is defined in the static class.
As DateTime
class is already taken above and hence we have not taken this class for the explanation.
Below is the example
//This is a existing Calculator class which have only one method(Add)
public class Calculator
{
public double Add(double num1, double num2)
{
return num1 + num2;
}
}
// Below is the extension class which have one extension method.
public static class Extension
{
// It is extension method and it's first parameter is a calculator class.It's behavior is going to extend.
public static double Division(this Calculator cal, double num1,double num2){
return num1 / num2;
}
}
// We have tested the extension method below.
class Program
{
static void Main(string[] args)
{
Calculator cal = new Calculator();
double add=cal.Add(10, 10);
// It is a extension method in Calculator class.
double add=cal.Division(100, 10)
}
}