Why is this code invalid in C#?

The compiler requires that either the types of second and third operands are the same, or that one is implicitly convertible to the other. In your case, the types are DBNull and string, neither of which is implicitly convertible to the other. Casting either of them to object solves that.

EDIT: Looks like it is indeed legal in Java. Quite how it works out what to do when it comes to method overloading, I’m not sure… I’ve just looked at the JLS, and it’s extremely unclear about what the type of the conditional is when there are two incompatible reference types involved. The C# way of working may be more irritating occasionally, but it’s clearer IMO.

The relevant section of the C# 3.0 spec is 7.13, the conditional operator:

The second and third operands of the
?: operator control the type of the
conditional expression. Let X and Y be
the types of the second and third
operands. Then,

  • If X and Y are the same type, then this is the type of the conditional
  • Otherwise, if an implicit conversion (§6.1) exists from X to Y,
    but not from Y to X, then Y is the
    type of the conditional expression.
  • Otherwise, if an implicit conversion (§6.1) exists from Y to X,
    but not from X to Y, then X is the
    type of the conditional expression.
  • Otherwise, no expression type can be determined, and a compile-time
    error occurs.

Leave a Comment