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.
.ToString()Handles NULL values even if variable value becomes null, it doesn't show the exception. 1. It will not handle NULL values; it will throw a NULL reference exception error. 2.
Null and toString()toString() is only called implicitly if the object passed isn't null. If it is, the literal "null" is printed instead. String s = (o !=
Returns: a string representation of the object. In other words null is not a defined return value. If you don't override the toString() method then you will always get a string that at least gives you the Object's ID.
No method can be called on a null object. If you try to call ToString() on a null object it will throw a NullReferenceException . The conclusion “if it returns null still then the object is null” is not possible and thus wrong.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With