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();

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s