About Links Archives Search Feed Albums of Note

C# Extension Methods Are Great

I’ve had a little time recently to look through the new features in C# 3.0 and while all new features while have their uses immeidately, its got to be extension methods that strike the first chord in the refactoring crazy world. The premise is simple. Rather than calling a static helper class on a variable, an extension method extends the base class of your variable making things that much nicer and, when VS has been updated properly, the extension method will be available in Intellisense too.

Lets take an example. Phil Haack blogged about IsNullOrEmpty() [http://haacked.com/archive/2006/08/23/String.IsNullOrEmpty.aspx] a little while ago - a simple function that returns true if a given string is null or empty. Typically, it will be called like so from a static helper class

if (StringHelper.IsNullOrEmpty(myString)) { … }

which is fine if a little difficult to read. Rewriting IsNullOrEmpty() as an extension method allows you to call it like so

if (myString.IsNullOrEmpty()) { … }

which is much nicer. And what do you have to do to get this running? Add one word - this - to the first parameter of the function.

private bool IsNullOrEmpty(this string value) { if (value != null) { return (value.Length == 0); } return true; }

I like this. It took about five minutes to turn Chad Finsterwald’s string utility library [http://developer.coreweb.com/articles/Default5.aspx] into a set of string extension methods, making sure that each new method called the extension methods correctly and I added a few of my own in too. Download it here [/file.axd?file=stringextensions.zip] for comparison to Chad’s C# 2.0 library and full kudos to him for writing it. For those interested, the C#3.0 Preview is part of the LINQ [http://msdn.microsoft.com/data/ref/linq/] CTP which you can download here [http://www.microsoft.com/downloads/details.aspx?familyid=1e902c21-340c-4d13-9f04-70eb5e3dceea&displaylang=en] .

Now then, where’s my DateTimeExt library?

Posted on September 21, 2006   #Geek Stuff  

← Next post    ·    Previous post →