There is no implicit conversion between null and null

I have this weird piece of code (that will never, ever be used in production code) that produces a weird compilation error and I'd want to know more about this behavior,

string MyMethod(string s)
{
   return s == null ? null : null;
}

The error I get is:

Type of conditional expression cannot be determined because there is no implicit conversion between null and null

What explains this behavior?

Jon Skeet
people
quotationmark

What explains this behavior?

The C# 5 specification, section 7.14:

The second and third operands, x and y, of the ?: operator control the type of the conditional expression.

  • If x has type X and y has type Y then [...]
  • If only one of x and y has a type, and both x and y, of are implicitly convertible to that type, then that is the type of the conditional expression.
  • Otherwise, no expression type can be determined, and a compile-time error occurs.

Your situation is the last of these options - the expression null has no type, therefore neither x and y have a type, therefore you get a compile-time error.

The fact that you're trying to use the result of the conditional operator expression has no bearing on the type of the expression - the compiler works from the "inside out" as it were - it finds the type of the expression and then checks that your usage of it is correct.

In this case, there is no type, therefore compilation fails.

In C# 1, there was a "null type" which was regarded as the type of the null literal - but that concept was removed in the C# 3 specification. (There was no full C# 2 specification from MS; it was merely a set of additions to the C# 2 specification.)

people

See more on this question at Stackoverflow