CodeSOD: Extended and Empty
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();
Which is... an interesting behavior. This code is old enough that it might predate .NET's addition of nullable types, which it ends up sort of imitating, though I think that's more of an accident.
This makes the code weirder, and certainly would confuse someone not used to the codebase. I'm sure the original developer thought it was mighty convenient though.
[Advertisement] Continuously monitor your servers for configuration changes, and report when there's configuration drift. Get started with Otter today!