Appearance
Extension Methods
Extension methods allow you to add methods to existing types without modifying them. They provide a way to extend the functionality of types you don't control or can't inherit from.
Creating Extension Methods
Extension methods are defined in static classes and use the this
keyword to extend an existing type. They appear as instance methods on the extended type.
csharp
public static class StringExtensions
{
public static int WordCount(this string str)
{
return str.Split(new char[] { ' ' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
Using Extension Methods
Once defined, extension methods can be called as if they were instance methods of the extended type. This provides a clean and intuitive syntax.
csharp
string text = "Hello World";
int wordCount = text.WordCount(); // Using the extension method