I would like to do something like this :
int? l = lc.HasValue ? (int)lc.Value : null;
where lc is a nullable enumeration type, say EMyEnumeration?. So I want to test if lc has a value, so if then give its int value to l, otherwise l is null. But when I do this, C# complains that 'Error type of conditional expression cannot be determined as there is no implicit conversion between 'int' and ''.
How can I make it correct? Thanks in advance!!
You have to cast null
as well:
int? l = lc.HasValue ? (int)lc.Value : (int?)null;
By the way, that's one of the differences between the conditional operator and an if-else
:
if (lc.HasValue)
l = (int)lc.Value;
else
l = null; // works
The relevant C# specification is 7.14 Conditional operator:
The second and third operands, x and y, of the ?: operator
control the type of the conditional expression.
Since int
is not convertible to null
implicitly and vice-versa you get a compiler error. But you could also cast the enum
to int?
instead of int
which is convertible. Then the compiler can derive the type and it'll compile:
int? l = lc.HasValue ? (int?)lc.Value : null; // works also
or, as Sergey has mentioned in his answer, directly:
int? l = (int?)lc;