codymanix codymanix - 8 months ago 57
C# Question

How to do ToString for a possibly null object?

Is there a simple way of doing the following:

String s = myObj == null ? "" : myObj.ToString();

I know I can do the following, but I really consider it as a hack:

String s = "" + myObj;

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

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


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

to be even more concise.

Edit: 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()


I keep receiving up-votes for this answer, but I would like to say that while it maybe appears elegant, the cast is almost always necessary and therefore is not that succinct in practice, and possibly harder to read than several other answers.

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();

C# 6.0 Edit:

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

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

Or even:

string s = $"{myObj}";