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!
.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.
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With