2008-02-03

The simplest reason to like C# Extension Methods

I like extension methods because I can finally compare strings without stupid boilerplate:


string nullity = null;
string maybeNullity = string.Empty;
if (nullity.CompareEquals(maybeNullity, true)) {...}

public static bool CompareEquals(this string strA, string strB, bool ignoreCase)
{
return (0 == string.Compare(strA, strB, ignoreCase, CultureInfo.CurrentCulture));
}


It would seem extension methods encourage more "OOP style" syntax when using statics. Even though the variable "nullity" is null, it won't throw a NullReferenceException because it's really just a parameter to static function. The string.Compare method that uses the null variable checks for null and handles it safely.


UPDATE: PeterB refuted my statements with solid arguments:
Uh, no. Using member function syntax does precisely nothing to make code object-oriented.

I personally prefer to have tools that reject statically detectable null pointer dereferences, and this kind of a construct would probably confuse them.

Moreover, in a symmetric test such as that one, it's simply bizarre to want to use method syntax. Neither the left hand side nor the right hand side is more important than the other; a non-member is a much more appropriate way to call the function.

0 comments: