Extension Methods in C#
As its name itself indicates that it extends the functionality of an existing type in .NET. By using extension method you can add methods to existing types without creating a new derived type. There is no need of recompiling, or modify the original types. If you want to add new methods to a type, without having the source code of that type, then you can implement extension methods.
To create an extension method, make the method static and pass this keyword as a first parameter.
public static int Square(this int i)
To define an extension method, first of all, define a static class. For example, we have created an ExtensionMethod class in the following example. The ExtensionMethod class will contain all the extension methods. You can provide any name for class according to your need.
You can create separate static class in your project or you can create class library project. If you have created class library, then you have to add the reference. I created a class in ConsoleApplication1 project.
Open visual studio, create new console application. Right click on onsoleApplication1 in solution explorer and add new class. Name it as
ExtensionMethod.
namespace ConsoleApplication1
{
public static class ExtensionMethod
{
//It will calculate factorial of an integer value
public static int Factorial(this int n)
{
int fact = 1;
for (int j = n; j > 0; j--)
{
fact =fact * j;
}
return fact;
}
// This method will calculate square of an integer value
public static int Square(this int i)
{
return i * i;
}
}
}
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number to find the square and factorial");
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Square of {0} is {1}", n, n.Square());
Console.WriteLine("Factorial of {0} is {1}", n, n.Factorial());
Console.ReadLine();
}
}
}
When you write the integer n and type dot the Square() and Factorial() extension methods will come automatically.
Key things about Extension Methods:
- Extension Methods must be located in a static class.
- Extension Methods are static methods.
- 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.
- When we press the dot (.) after a type instance, then Extension Methods will come in VS intellisense.
- An extension method should be in the same namespace, if not then you have to import the namespace of the class by a using statement.