Here\'s the scenario...
if (entry.Properties[\"something\"].Value != null)
attribs.something = entry.Properties[\"something\"].Value.ToString();
<
To do precisely what you're trying to do a helper method can always be used:
CopyIfNotNull(entry.Properties["something"].Value, out attribs.something);
void CopyIfNotNull(string src, out string dest)
{
if(src != null)
dest = src;
}
attribs.something = string.Format("{0}",entry.Properties["something"].Value)
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();
}
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();
// ^^
attribs.something = String.Format("{0}", entry.Properties["something"].Value);
Not sure about performance though...
Is it somehow possible to do something like Dale Ragan's answer above, but overriding ToString() instead of creating a new NullSafeToString() method? I'd like this (or returning "null") to be the default behaviour. The compiler (Visual C# 2010 Express) doesn't complain when I add the following method to public static class ObjectExtensions, but the method doesn't get called...
public static String ToString(this Object obj)
{
if (obj == null)
{
return "null";
}
else
{
return obj.GetType().Name;
}
}