I have foo (object) and foo2 (string) in  a C# console application. The Code 2 throws exception while Code 1 works fine.
Can you please explain why it is behaving so (with MSDN reference)?
// Code 1
object foo = null;
string test = Convert.ToString(foo).Substring(0, Convert.ToString(foo).Length >= 5 ? 5 : Convert.ToString(foo).Length);
// Code 2
string foo2 = null;
string test2 = Convert.ToString(foo2).Substring(0, Convert.ToString(foo2).Length >= 5 ? 5 : Convert.ToString(foo2).Length);
                From the documentation of Convert.ToString(string):
Return Value
Type:System.String
value is returned unchanged.
So null input will result in a null return value.
From the documentation of Convert.ToString(object):
Return Value
Type:System.String
The string representation of value, orString.Emptyif value is null.
(Where "Nothing" means "null" here.)
So null input will result in an empty string (non-null reference) return value.
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