简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM