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();
}
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();
Convert.ToString(entry.Properties["something"].Value);
Adding an empty string to an object is a common idiom that lets you do null-safe ToString
conversion, like this:
attribs.something = ""+entry.Properties["something"].Value;
When entry.Properties["something"].Value
is null
, this quietly returns an empty string
.
Edit: Starting with C# 6 you can use ?.
operator to avoid null
checking in an even simpler way:
attribs.something = entry.Properties["something"].Value?.ToString();
// ^^
Can you not do:
attribs.something = entry.Properties["something"].Value as string;