Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for null before ToString()

Here's the scenario...

if (entry.Properties["something"].Value != null)   attribs.something = entry.Properties["something"].Value.ToString(); 

While effective and working correctly, this looks ugly to me. If I don't check for a null before performing the ToString() then it throws an exception if the property was null. Is there a better way to handle this scenario?

Much appreciated!

like image 464
Dscoduc Avatar asked Feb 15 '09 05:02

Dscoduc


People also ask

Does ToString work on 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.

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.

What is the difference between convert Tosting () and ToString () method?

ToString method displays a blank line but output using ToString method throws an un-handled exception. Convert. ToString handles null while ToString doesn't and throws a NULL reference exception.

What is ToString method in C#?

ToString is the major formatting method in the . NET Framework. It converts an object to its string representation so that it is suitable for display.


2 Answers

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(); } 
like image 65
Rex M Avatar answered Sep 28 '22 00:09

Rex M


If you are targeting the .NET Framework 3.5, the most elegant solution would be an extension method in my opinion.

public static class ObjectExtensions {     public static string NullSafeToString(this object obj)     {         return obj != null ? obj.ToString() : String.Empty;     } } 

Then to use:

attribs.something = entry.Properties["something"].Value.NullSafeToString(); 
like image 42
Dale Ragan Avatar answered Sep 28 '22 02:09

Dale Ragan