C# extension methods are a way to extend the functionality of existing classes, structures or interfaces without having to modify their source code. They are defined as static methods in a static class, and the first parameter of the method must be preceded by the this
keyword, which indicates that the method is an extension method.
Here’s an example of how you can define an extension method:
using System;
namespace ExtensionMethodsExample
{
public static class StringExtensionMethods
{
public static string Reverse(this string input)
{
char[] characters = input.ToCharArray();
Array.Reverse(characters);
return new string(characters);
}
}
}
Now, you can use this extension method just like any other method on a string instance:
using System;
namespace ExtensionMethodsExample
{
class Program
{
static void Main(string[] args)
{
string input = "hello";
string reversed = input.Reverse();
Console.WriteLine(reversed);
}
}
}
When you run this code, you will see the output olleh
, which is the reversed string.
Here’s another example, this time extending the int
type:
using System;
namespace ExtensionMethodsExample
{
public static class IntExtensionMethods
{
public static int Square(this int input)
{
return input * input;
}
}
}
And again, you can use this extension method like any other method on an int
instance:
using System;
namespace ExtensionMethodsExample
{
class Program
{
static void Main(string[] args)
{
int input = 5;
int result = input.Square();
Console.WriteLine(result);
}
}
}
When you run this code, you will see the output 25
, which is the square of the input 5
.
Note that extension methods are compiled as regular static methods, but the this
keyword makes them appear as if they were instance methods of the type being extended. This makes them a convenient way to add functionality to existing types, without having to modify their source code.