Extension methods are a new feature in C# 3.0. An extension method enables us to add methods to existing types without creating a new derived type, recompiling, or modify the original types. We can say that it extends the functionality of an existing type in .NET. An extension method is a static method to the existing static class. We call an extension method in the same general way; there is no difference in calling.
Feature and property of extension method
1. It is a static method.
2. It must be located in a static class.
3. It uses the "this" keyword as the first parameter with a type in .NET and this method will be called by a given type instance on the client side.
4. It also is shown by VS intelligence. When we press the dot (.) after a type instance, then it comes in VS intelligence.
5. An extension method should be in the same namespace as it is used or you need to import the namespace of the class by a using statement.
6. You can give any name for the class that has an extension method but the class should be static.
7. If you want to add new methods to a type and you don't have the source code for it, then the solution is to use and implement extension methods of that type.
8. If you create extension methods that have the same signature methods as the type you are extending, then the extension methods will never be called.
Below is the procedure on how to extend the class and hence we have taken a
calculator
class to explain it. And we are creating another class Extension and adding static method.
//This is an existing Calculator class which have only one method(Add)
public class Calculator
{
public double Add(double num1, double num2)
{
return num1 + num2;
}
}
//Extension method class
public static class Extension
{
public static double Division(this Calculator cal, double num1, double num2)
{
return num1 / num2;
}
}
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)
Console.Read();
}
}
Nice explanation
ReplyDelete