C# Extension Methods Are Great

by DanM 21. September 2006 17:40

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() 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 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 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 CTP which you can download here.

Now then, where’'s my DateTimeExt library?

Powered by BlogEngine.NET 1.6.0.0
Theme by Mads Kristensen, adapted by Dan Maharry

About Dan

Dan Maharry Dan Maharry
Web developer at Co-operative Web and tech writer. More...
Creative Commons License View Dan's bookmarks on Delicious LinkedIn Facebook Facebook Last.fm
Last.fm Twitter Subscribe to Dans RSS Feed Download Dans OPML File Add blog to technorati favorites

RecentComments

Comment RSS