Check for null before calling ToString()

Handy little snippet of code for checking for null before calling ToString().

I found this little bit of code pretty clever and handy.

Let us avoid those errors:

private static string ToSafeString(object obj)
{
   return (obj ?? string.Empty).ToString();
}

Source

Posted in C#

Leave a Reply