Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional expression inside Convert.ToString() evaluating wrong?

Tags:

c#

I'm stumped. Why wouldn't the first and fourth lines evaluate to null?

null wut

Post-answer edit:

For the benefit of others, the desired behavior would be created by using:

boolFoo ? null : Convert.ToString(DBNull.Value)

This works because Convert.ToString() and null imply a common type of string.

like image 907
bblack Avatar asked Apr 08 '26 09:04

bblack


2 Answers

From MSDN's documentation for the ?: operator:

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

In this case, it looks like null is being implicitly converted to System.Object. From a little further digging into MSDN's documentation, Convert.ToString(Object value) returns String.Empty if value is null.

This is not the same as in the sixth line in your post, as Convert.ToString(null) does not implicitly convert null to System.Object (since you are not using the ?: operator).

like image 58
Donut Avatar answered Apr 09 '26 23:04

Donut


It looks like they do evaluate to null, but Convert.ToString(object) returns null values as String.Empty.

Edit per OP's comment

In the case of Convert.ToString(string), the string is simply returned, even if null. Courtesy of Reflector:

public static string ToString(string value)
{
  return value;
}
like image 45
Phil Hunt Avatar answered Apr 09 '26 22:04

Phil Hunt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!