C# Extension Methods
Extension methods allow you to add new methods to existing types without modifying the original type or creating a new derived type.
They are a powerful feature that enables you to extend the functionality of classes, interfaces, or structs, even if you don't have access to the source code.
Here's a basic overview of how extension methods work.
Define a static class
Create a static class to contain your extension methods. This class must be static.
public static class MyExtensions
{
// Extension methods will be defined here
}
Define extension methods
Create static methods within the static class, and use the this
keyword followed by the type you want to extend as the first parameter. The this
keyword indicates that the method is an extension method for the specified type.
public static class MyExtensions
{
public static int Square(this int number)
{
return number * number;
}
public static string Reverse(this string input)
{
char[] charArray = input.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
}
Usage
You can now use these extension methods as if they were instance methods of the extended type.
using System;
class Program
{
static void Main()
{
int num = 5;
int squared = num.Square();
Console.WriteLine($"Square of {num} is {squared}");
string text = "Hello";
string reversed = text.Reverse();
Console.WriteLine($"Reversed text: {reversed}");
}
}
In this example, Square
and Reverse
are extension methods for int
and string
, respectively. They can be called as if they were regular methods of those types.
Remember the following points about extension methods:
1. They must be in a static class.
2. They must be static methods.
3. The first parameter of the method must have the this
modifier followed by the type being extended.
4. You need to import the namespace containing the static class with the extension methods to use them in your code.