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!

4/26/2009 4:44:52 PM

Accepted Answer

Update 8 years later (wow!) to cover c# 6's null-conditional operator:

var value = maybeNull?.ToString() ?? ""

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();
3/11/2017 2:07:21 PM

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow