Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert.ToString behaves differently for "NULL object" and "NULL string"

Tags:

c#

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);
like image 599
LCJ Avatar asked Nov 22 '12 14:11

LCJ


1 Answers

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, or String.Empty if value is null.

(Where "Nothing" means "null" here.)

So null input will result in an empty string (non-null reference) return value.

like image 75
Jon Skeet Avatar answered Oct 14 '22 02:10

Jon Skeet