C# / Programming

C# extension methods

C# extension methods are a little bit like magic: it enables you to add functionality to an already existing object, without creating a new class. If we have a string object, that we use as an email field, we can add a little helper extension method that will assist us checking:

public static bool IsValidEmail(this string s) { if (s == null) return false; if (s.Length < 3) return false; Regex regex = new Regex(@"\w[\w\.]*@\w[\w\.]*"); if (regex.IsMatch(s)) return true; return false; }
Code language: C# (cs)

Note the special method signature: the this string is quite brilliant; suggesting that this is a (technically) a function, but indeed a method over a string.

This is pretty cool; the string class doesn’t really have an IsValidEmail method; but now, technically, it does.

Now, this is one of the great things about c#, that doesn’t exists in many of the other languages – you don’t need to derive another class from string, you don’t need to have an annoying set of supplemental functions, you just call the method on the object you’ve already gotten.


Like anything, this come with a price: One thing, if you miss the implementation part, your “super string” is now a regular string. If your extension reside in a library (which is very reasonable) and this library is not present you’ll get an error. Easy to deal with when you’re the one who is writing the extension, less so if you’re just using it. “OK” you’ll say, “but there is no such method in the string class, the user should know that this is an extension”. Well, technically, that’s right. But some users will not check. Further more, if we’re using a less known object, this gets more complicated. And if we’re pulling back a dynamic class (please don’t) we’re headed to a runtime error.

Best practice

Use extensions, they are great, but make sure they are found in the right place. I’d suggest a company::extensions name space. Then, when you are using them, the using statement makes it clear:

using Talreg.Extensions.Strings; // more code here string address=""; Assert.False(address.IsValidEmail());
Code language: C# (cs)

Any programmer who is now maintaining this code, can see this name space. And clear code is always better than documentation.

Leave a Reply

Your email address will not be published. Required fields are marked *