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