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.
That's documented behaviour
Convert.ToString Method (Object)
The string representation of value, or String.Empty if value is null.
Convert.ToString Method (String)
value is returned unchanged.
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