Extension methods are teh shit! | Johan Driessen

Extension methods are teh shit!

I’m really starting to like extension methods! I must admit I was a bit sceptical at first when they appeared in C# 3.0 (wow, that was 3 years ago!). I was worried that they would make the code hard to follow, and thought that you could just make a static helper class instead (which is, after all, what extension methods really are).

1
2
3
4
5
//After all, what's wrong with this?
cleanString = StringHelper.RemoveHtml(htmlString);

//On the other hand, this does look nicer...
cleanString = htmlString.RemoveHtml();

So at first, I didn’t use it for much, but now I’ve really started to like it, and I find myself extract anything that operates on classes I can’t change to extension methods. For example, don’t you hate that you can’t use Action.ForEach on IEnumerable? Don’t worry, there’s an extension for that:

1
2
3
4
5
6
7
public static void ForEach<T>( this IEnumerable<T> enumeration, Action<T> action )
{
foreach (var item in enumeration)
{
action( item );
}
}

And the ugly !string.IsNullOrEmpty(someStringThatMayBeNullOrEmpty)? Well, how about

1
2
3
4
5
6
public static bool IsNullOrEmpty(this string @string, bool trim = false)
{
if (@string == null)
return true;
return String.IsNullOrEmpty(trim ? @string.Trim() : @string);
}

And suddenly you can call it like this instead: !someStringThatMayBeNullOrEmpty.IsNullOrEmpty(). And yes, this works even if the string is null, since you’re not actually calling a method on the string object, but rather a static method with the string as a parameter!

I’m also very fond of a generic extension that lets me parse strings to enums with an optional fall-back value if the string doesn’t parse: enumString.ParseToEnum<MyEnum>(MyEnum.DefaultValue). I expect that if this keeps up, all logic will be in extension methods by the end of the year.

For some reason, my colleagues thought that I went a bit to far with this one:

1
2
3
4
public static bool ContainsSomething( this string str )
{
return !str.IsNullOrEmpty();
}

But I think they’re just jealous.

Update: Fixed some bad formatting…