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):So
nullinput will result in anullreturn value.From the documentation of
Convert.ToString(object):(Where “Nothing” means “null” here.)
So
nullinput will result in an empty string (non-null reference) return value.