Why does null need to be casted?

Posted by BlueRaja The Green Unicorn on Stack Overflow See other posts from Stack Overflow or by BlueRaja The Green Unicorn
Published on 2010-04-09T15:54:03Z Indexed on 2010/04/09 16:03 UTC
Read the original article Hit count: 364

Filed under:
|
|
|

The following code does not compile:

//int a = ...
int? b = (int?) (a != 0 ? a : null);

In order to compile, it needs to be changed to

int? b = (a != 0 ? a : (int?) null);

Since both b = null and b = a are legal, this doesn't make sense to me.

Why does null need to be casted, and why can't we simply cast the whole expression (which I know is legal in other cases)?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET