Extension Methods in C#
Introduction
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. They are defined as static methods but are called using instance method syntax.
Creating an Extension Method
To create an extension method, define a static class to contain the extension method. This class must be static:
public static class StringExtensions { public static string FirstLetterToUpperCase(this string str) { if (string.IsNullOrEmpty(str)) return str; return char.ToUpper(str[0]) + str.Substring(1); } }
In this example, we created a static class StringExtensions
that contains the extension method FirstLetterToUpperCase
.
Using the Extension Method
Using the extension method is straightforward. You call it as if it were a method on the type:
public class Program { public static void Main() { string example = "hello world"; string result = example.FirstLetterToUpperCase(); Console.WriteLine(result); // Output: Hello world } }
Notice how we called FirstLetterToUpperCase
on the string instance example
as if it were an instance method.
Rules for Extension Methods
There are some rules to keep in mind when creating and using extension methods:
- Extension methods must be defined in a static class.
- Extension methods must be static methods themselves.
- The first parameter of the extension method must be
this
followed by the type it is extending. - They are called in the same way as instance methods on the extended type.
Real-World Example
Let's take a look at a more practical example. Suppose we want to add a method to the List<T>
class that filters the list based on a predicate:
public static class ListExtensions { public static ListFilter (this List list, Func predicate) { List result = new List (); foreach (T item in list) { if (predicate(item)) { result.Add(item); } } return result; } }
We can now use this extension method to filter a list:
public class Program { public static void Main() { Listnumbers = new List { 1, 2, 3, 4, 5, 6 }; List evenNumbers = numbers.Filter(n => n % 2 == 0); foreach (var num in evenNumbers) { Console.WriteLine(num); // Output: 2, 4, 6 } } }
In this example, we created a Filter
method that allows us to filter the elements of a List<T>
based on a given predicate.
Conclusion
Extension methods are a powerful feature in C# that allows you to extend existing types with new methods without modifying their source code. This can lead to more readable and maintainable code. By following the simple rules and guidelines, you can create your own extension methods to make your code more expressive and concise.