Convert.ToString returns string.empty instead of null

  • A+
Category:Languages

I've found out a strange behaviour of Convert.ToString and I would like to understand, why it does behave like this.

Have a look at following code pieces:

string obj = null; var str = Convert.ToString(obj); Console.WriteLine(str); // CORRECT: returns null; 

all good so far, but:

DBNull obj = DBNull.Value; var str = Convert.ToString(obj); Console.WriteLine(str); // ???: returns string.Empty ("") 

and

object obj = null; var str = Convert.ToString(obj); Console.WriteLine(str); // ???: returns string.Empty ("") 

It looks to me like a bug, because when i do a conversion to a string and the input is NULL the result should be default of a string, which is also NULL.

 


Convert.ToString has a String overload that does nothing:

Returns the specified string instance; no actual conversion is performed.

and its Object overload is defined thus:

The string representation of value, or String.Empty if value is null.

It might be a bit surprising, but there’s no reason to use Convert.ToString on a String expression in the first place.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: