Extension method
Let some methods are already defined inside a class or structure and you want to add another new method to that class or structure. But there may be many types of limitations or constraints in adding a new method to the class/structure, such as:-
- It may happen that the source code of the class or structure is not available, so it will not be possible to create a new method within that class or structure.
- It may happen that that class is a sealed class. Therefore, it is not possible to create its child class using inheritance.
- It may also happen that the type is a struct then we cannot create new child struct because struct doesn't support inheritance.
- It may be possible to inherit the class, but creating a new method in child class will force recompilation of code. But what if the recompilation of project is not desired.
Therefore, we see that creating a new method of a class( or struct) is either not possible or in many circumstances, project manager might be reluctant to extend the existing class, considering the side effects of the newly created method.
Keeping the above constraints in mind, if a new method is to be created for a class, then it should be created in a completely new class and this class should be bound together with the old class as if the method is created in the old class. The newly created method is called by help of old class as if the method is the member of old class, although the method is defined in a new class. Such method is called extension method.
The class of the extension method must be a static class so that the binding of the new extension method to the other class is done only at the time of loading. We know that there are only static methods within a static class.
This is the specialty of extension methods, they must have a parameter with them. This first parameter refers to the class or type with which the extension method is to be bonded.
In other words, extension method is static method from coding point of view but non-static method from behavioral point of view. Behaviorally, extension method is the method of non-static class because extension method is called by the object of the class, not as the method of static class.
Note that when compiling the source code of a class with an extension method, the binding with the old class is done at the time of class loading and no recompilation of the old code is required. In this way, only the code of the new class is compiled, and by binding the method of that new class to the old class, the new extension method can be called by the object of the old class.
To bind the method of the new class to the old class, a reference to the old class is given as the first parameter of the method of the new class, which is called the extension method, and the this keyword is used before that reference type. Is. We can understand this concept better through example.
using System;
namespace ExtensionMethodEx
{
class Class1
{
public void Display()
{
Console.WriteLine("Normal Method in Class1.");
}
}
}
using System;
namespace ExtensionMethodEx
{
static class Class2
{
public static void ExtensionMethod1(this Class1 class1)
{
Console.WriteLine("This extension method bound with Class1 objects.");
}
}
}
using System;
namespace ExtensionMethodEx
{
class Program
{
static void Main(string[] args)
{
Class1 c1 = new Class1();
c1.Display();
c1.ExtensionMethod1();
//Another approach to call
Class2.ExtensionMethod1(c1);
Console.ReadKey();
}
}
}
In C#, extension method is used to add a new method to a class. When this new method is tied to a class, then this new method can be called by the object of that class. It is not that the new method is added by coding within the class, in fact, the extension method is created inside a new static class and this new static class is bound to the class with which it has to be included. . Therefore, by extension method, it means to bind a static method of a static class with another class so that that static method can be called by an object of another class using it as a non-static method.
Note. An extension method is possible for an interface. When you write an extension method for an interface, any class that implements that interface automatically gains access to that method.
Example
using System;
// 1. Define the interface
public interface ILogger
{
void Log(string message);
}
// 2. Create a static class for the extension method
public static class LoggerExtensions
{
// Notice the 'this' keyword before the interface type
public static void LogError(this ILogger logger, string errorMessage)
{
logger.Log($"[ERROR] {DateTime.Now}: {errorMessage}");
}
}
// 3. Implement the interface in a class
public class ConsoleLogger : ILogger
{
public void Log(string message)
{
Console.WriteLine(message);
}
}
// 4. Usage
public class Program
{
public static void Main()
{
ILogger myLogger = new ConsoleLogger();
// Calling the extension method as if it belongs to the interface
myLogger.LogError("Something went wrong!");
}
}
Why Use Extension Methods?
Reasons for using an extension method:
- The source code of class/struct/interface is not available.
- It is not possible to create derived type (e..g. type is sealed class, type is struct). Note that struct is implicitly sealed and hence it is not possible to inherit structure.

No comments:
Post a Comment