CodeSOD: Extended and Empty

This post was originally published on this site

The Daily WTF

We’ve discussed extension methods in .NET in the past. If you write a method with a signature like public static void foo(this string input), then you can invoke this method like myString.foo(). It acts like an instance method to a caller, but it really just invokes foo(myString). It’s a nice way to inject functionality into existing classes, and many .NET libraries use this feature.

Esromhaz‘s co-worker found an… application of this.

public static bool IsNullOrEmpty(this string str) { return string.IsNullOrEmpty(str); } public static bool IsNotNullOrEmpty(this string str) { return !string.IsNullOrEmpty(str); }

Now, the default IsNullOrEmpty is a static method, because it has to be- if myString is null, I can’t call IsNullOrEmpty on it. That doesn’t make sense. But the co-worker clearly disagreed with this limitation and wanted it to look like an instance method.

So, this actually does work:

string myString = null; bool isNull = myString.IsNullOrEmpty();

To read the full article click on the 'post' link at the top.