Monday, November 26, 2007

String extension methods

I got really tired of the IsNullOrEmpty static method, so I converted it into an extension method:

public static class StringExtensions
    public static bool IsNullOrEmpty(this string value)
        return string.IsNullOrEmpty(value);

Since that method was already static, I just put a simple wrapper around it.  All scenarios pass:

public void Matches_existing_behavior()

    string value = null;


    value = string.Empty;


    value = "blarg";


The only rather strange thing about extension methods is that they can be called by null references, as shown in the test above.  As long as everyone understands that extension methods are syntactic sugar and not actually extending the underlying types, I think it's clear enough.

The extension method is more readable and lets me work with strings instead of having to remember that it's a static method.  Static methods that reveal information about instances of the same type seem to be prime candidates for extension methods.

1 comment:

Adi said...

Oes Tsetnoc one of the ways in which we can learn seo besides Mengembalikan Jati Diri Bangsa. By participating in the Oes Tsetnoc or Mengembalikan Jati Diri Bangsa we can improve our seo skills. To find more information about Oest Tsetnoc please visit my Oes Tsetnoc pages. And to find more information about Mengembalikan Jati Diri Bangsa please visit my Mengembalikan Jati Diri Bangsa pages. Thank you So much.
Oes Tsetnoc | Semangat Mengembalikan Jati Diri Bangsa