mo.notono.us

Wednesday, May 05, 2004

Boxing and ? :

There is an inconsistency in C# that I find somewhat annoying: The following code will break:
int i = 0;
object o = (i == 0) ? null : i;
The error message is that "There is no implicit conversion between 'null' and 'int'." - as if we're trying to assign null to i, which of course we're not. The following works fine (of course):
int i = 0;
object o;
if (i == 0) 
  o = null;
else 
  o = i;
and also:
int i = 0;
object o = (i == 0) ? null : (object)i;
My problem isn't so much with the fact that the original code won't compile, but rather that the error message is simply wrong and misleading.

Links to this post:

Create a Link

<< Home