Extension methods in C# allow developers to add new methods to existing types without modifying their source code. This powerful feature enhances code readability and promotes cleaner, more maintainable code.
Extension methods are static methods that can be called as if they were instance methods on the extended type. They provide a way to "extend" existing types, including those you don't have control over, such as .NET framework classes.
To create an extension method:
this
keywordHere's a basic example:
public static class StringExtensions
{
public static string Capitalize(this string input)
{
if (string.IsNullOrEmpty(input))
return input;
return char.ToUpper(input[0]) + input.Substring(1);
}
}
Now you can use this method on any string:
string name = "john";
Console.WriteLine(name.Capitalize()); // Output: John
LINQ (Language Integrated Query) heavily relies on extension methods. Many LINQ operators are implemented as extension methods on IEnumerable<T>
.
var numbers = new[] { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
In this example, Where
is an extension method provided by LINQ.
While powerful, extension methods have some limitations:
Extension methods are a versatile feature in C# that enable developers to enhance existing types without modifying their source code. By understanding their syntax, use cases, and best practices, you can leverage extension methods to write more expressive and maintainable code.
For more advanced C# concepts, explore generics and lambda expressions.