Checking for null before ToString()

Update 8 years later (wow!) to cover c# 6’s null-conditional operator:

var value = maybeNull?.ToString() ?? String.Empty;

Other approaches:

object defaultValue = "default";
attribs.something = (entry.Properties["something"].Value ?? defaultValue).ToString()

I’ve also used this, which isn’t terribly clever but convenient:

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

Leave a Comment