08 Feb 2024
Extension methods in C# allow you to add new methods to existing types without modifying, deriving, or recompiling the original type. They were introduced in C# 3.0 as a feature to enhance the language's expressiveness and flexibility.
Here are some key points about extension methods:
-
Syntax: Extension methods are defined as static methods in static classes. They use the
thiskeyword as the first parameter of the method, specifying the type to which the method applies. Thethisparameter indicates that the method is an extension method for instances of the specified type. -
Usage: Extension methods enable you to call custom methods as if they were instance methods of the extended type, providing syntactic sugar for method invocation. This means you can use dot notation to call the extension method on instances of the extended type.
-
Namespace: To use extension methods, you need to import the namespace containing the static class that defines the extension methods.
Here's a simple example of an extension method:
using System;
public static class StringExtensions
{
public static string ReverseString(this string input)
{
char[] chars = input.ToCharArray();
Array.Reverse(chars);
return new string(chars);
}
}
class Program
{
static void Main(string[] args)
{
string original = "hello";
string reversed = original.ReverseString();
Console.WriteLine(reversed); // Output: olleh
}
}
In this example:
StringExtensionsis a static class that contains the extension methodReverseString.- The
ReverseStringmethod takes astringas its first parameter (prefixed withthis), allowing you to call it directly on instances of thestringclass. - In the
Mainmethod, theReverseStringmethod is invoked on theoriginalstring instance, even thoughReverseStringis not a member of thestringclass itself.
Extension methods are a powerful feature in C# that enables you to extend the functionality of existing types and improve code readability and maintainability.