Extension methods allow us to extend/add methods to existing types.
- These are static methods.
- These methods are called on the type being extended.
Extension Method
namespace MyConsoleApp
{
public static class MyExtensionMethods
{
public static int WordCount(this String str)
{
return str.Split(new char[] {' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
Extension Method Implementation
namespace MyConsoleApp
{
class Program
{
static void Main(string[] args)
{
string test = "This is a test";
Console.WriteLine(test.WordCount()); // OUTPUT: 4
}
}
}
Good To Know
- LINQ standard query operators are the most common extension methods.