How to Do Tostring for a Possibly Null Object

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

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

How to avoid Tostring exception if string is null?

I guess you are reading from data reader.

You will have to check if the value is null or DBNull and then you can call to string method.

    string user_guid = dr["user_guid"] != DBNull.Value && dr["user_guid"] != null ? dr["user_guid"].ToString() : null ; 

Hope this helps.

Any simple way to test null before convert an object to string

ObjectUtils.toString(object) from commons-lang. The code there is actually one line:

return obj == null ? "" : obj.toString();

Just one note - use toString() only for debug and logging. Don't rely on the format of toString().

Typescript, how to pass Object is possibly null error?

When you declare const overlayEl = useRef(null);
Makes the type it comes out as is null because that's the best possible inference it can offer with that much information, give typescript more information and it will work as intended.

Try....

 const overlayEl = useRef<HTMLDivElement>(null);

Alternatively some syntax sugar for if you don't care for when its undefined is to do something like this.

const overlayEl = useRef(document.createElement("div"))

using the above syntax all common DOM methods just return defaults such as "0" i.e overlayEl.offsetWidth, getBoundingClientRect etc.

Usage:

if(overlayEl.current) {
// will be type HTMLDivElement NOT HTMLDivElement | null
const whattype = overlayEl.current;
}

The way this works is typescripts static analysis is smart enough to figure out that if check "guards" against null, and therefore it will remove that as a possible type from the union of null | HTMLDivElement within those brackets.

Convert null object to String

Use this,

try {
deleteuserDetails.setCreatedBy(result.getPropertyAsString(0).toString());
}
catch(Exception e) {
deleteuserDetails.setCreatedBy("null");
}

What is the correct way to check for possibly null references?

In a multithreaded app boardMap[i,j] could potentially be set to null 10 nanoseconds after you've checked it not to be null. That's (probably) why the compiler now complains.
Of course it depends on your code.
If you're sure that array is only handled by one thread, your null check is safe as is and you can just ignore the warning here.

An easy way to protect you code in a multithreaded scenario (without locking) is to assign the array value to a local variable. And do the null check and the Console.Write on that variable. Then the null check is safe. See post by @GuruStron



Related Topics



Leave a reply



Submit