简体   繁体   中英

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?

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.)

The conditional operator needs to determine the type of its result based on the type of the second and third operands. null has no type, and so the conditional operator can't figure out what type its value will resolve to.

My suspicion is that the compiler is getting confused, because it can't determine what type is being returned. Based only on the information that it's null , it could be any reference type at all.

To fix it, cast one or both of your null s to be (string)null and it should understand.

Problem is that the result of the conditional operator cannot be infered from neither of the options, since neither specifies a type or inferes one. Solution can be to case either to string:

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

OF course, no need for this condition either, as it always returns null, instead it can be:

string MyMethod(string s)
{
   return null;
}

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