Is conditional expression inside Convert.ToString () incorrect?

I'm at a dead end. Why won't the first and fourth rows be null?

null wut

Editing after the answer:

In the interest of others, the desired behavior will be created using:

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

This works because Convert.ToString()and nullimply a common type string.

+3
source share
4 answers

From the MSDN documentation for the operator ?::

Any type first_expressionand second_expressionmust be the same, or there must be an implicit conversion from one type to another.

, , null System.Object. MSDN Convert.ToString(Object value) String.Empty, value null.

, , Convert.ToString(null) null System.Object ( ?:).

+3

, null, Convert.ToString(object) null String.Empty.

OP

Convert.ToString(string) , null. Reflector:

public static string ToString(string value)
{
  return value;
}
+2

Convert.ToString((DBNull)null) Convert.ToString(object), , null. .

Convert.ToString(null)causes overload Convert.ToString(string), as this is the most derivative applicable version. This overload returns the argument unchanged . This is why the sixth line evaluates to null.

+1
source

They null, this is only their type DBNull.

0
source

Source: https://habr.com/ru/post/1777524/


All Articles