How to do ToString for a possibly null object?

C# 6.0 Edit:

With C# 6.0 we can now have a succinct, cast-free version of the orignal method:

string s = myObj?.ToString() ?? "";

Or even using interpolation:

string s = $"{myObj}";

Original Answer:

string s = (myObj ?? String.Empty).ToString();

or

string s = (myObjc ?? "").ToString()

to be even more concise.

Unfortunately, as has been pointed out you'll often need a cast on either side to make this work with non String or Object types:

string s = (myObjc ?? (Object)"").ToString()
string s = ((Object)myObjc ?? "").ToString()

Therefore, while it maybe appears elegant, the cast is almost always necessary and is not that succinct in practice.

As suggested elsewhere, I recommend maybe using an extension method to make this cleaner:

public static string ToStringNullSafe(this object value)
{
    return (value ?? string.Empty).ToString();
}

string.Format("{0}", myObj);

string.Format will format null as an empty string and call ToString() on non-null objects. As I understand it, this is what you were looking for.


It would be great if Convert.ToString() had a proper overload for this.

There's been a Convert.ToString(Object value) since .Net 2.0 (approx. 5 years before this Q was asked), which appears to do exactly what you want:

http://msdn.microsoft.com/en-us/library/astxcyeh(v=vs.80).aspx

Am I missing/misinterpreting something really obvious here?