![]() |
VOOZH | about |
In C#, an extension method is a special kind of static method that allows you to add new methods to an existing type (class, struct or interface) without modifying its source code or creating a derived type. Extension methods are defined in a static class and are marked with the this keyword in their first parameter.
public static class ClassName{
public static ReturnType MethodName(this TargetType obj, parameters){
// method body
}
}
They are widely used to extend .NET types and interfaces, making code more readable and reusable. LINQ in C# is one of the most common examples of extension methods in action.
This example shows how to extend a built-in .NET type (string) with a custom method. We will add a WordCount method to count the number of words in a string.
Explanation:
Note: You can extend even sealed classes like string using extension methods, which cannot be inherited otherwise.
This example extends a user-defined class Student by adding a method PrintResult. The method evaluates whether the student has passed or failed, without modifying the original Student class.
In this example, we extend an interface ILogger. By defining the LogError extension method, every class implementing ILogger automatically gains this additional functionality without needing to redefine it.
NOTE: If an extension method is declared as public, then the type it extends (e.g., ILogger) must also be public. Otherwise, a compiler error occurs.