Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert.ToString returns string.empty instead of null

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.

like image 427
Benjamin Schäublin Avatar asked Nov 29 '22 08:11

Benjamin Schäublin


2 Answers

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.

like image 66
Ry- Avatar answered Dec 09 '22 14:12

Ry-


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.

like image 41
fubo Avatar answered Dec 09 '22 13:12

fubo