C# Extension Methods

Extension methods are new to me, I’d heard of them but never came across them before. The code below is lifted straight from the Microsoft docs. But it’s pretty straight-forward stuff.

Extension methods are useful when you have a want to extend a class where you don’t have access to the source, such as inbuilt types like int, or IList<T>, or classes that are sealed, or even that you just don’t want to extend for inheritance reasons.

Let’s say you want to count the words in a string:

namespace ExtensionMethods 
{
     public static class MyExtensions
     {
         public static int WordCount(this String str)
         {
             return str.Split(new char[] { ' ', '.', '?' },                               StringSplitOptions.RemoveEmptyEntries).Length;
         }
     }
} 

To use it:

using ExtensionMethods;
...
...
string s = "Hello Extension Methods";  
int i = s.WordCount();