Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 544
codymanix Avatar asked Oct 21 '10 12:10

codymanix


People also ask

Can you ToString a null?

.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.

Can you do ToString on null Java?

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 !=

What does ToString return for null?

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.

Can ToString return null C#?

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.


2 Answers

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(); } 
like image 163
Andrew Hanlon Avatar answered Sep 29 '22 03:09

Andrew Hanlon


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.

like image 29
Holstebroe Avatar answered Sep 29 '22 04:09

Holstebroe