This fails with a There is no implicit conversion between 'null' and 'int'
long? myVar = Int64.Parse( myOtherVar) == 0 ? null : Int64.Parse( myOtherVar);
However, this succeeds:
if( Int64.Parse( myOtherVar) == 0)
myVar = null;
else
myVar = Int64.Parse( myOtherVar);
Is there a way to make the ternary operator succeed?
The Compiler tries to evaluate the expressions from left to right
int64.parse
method return along
value not anullable
long value. so there is no conversion betweennull
andInt64.Parse( myOtherVar);
So, try this oneOR
long? myVar = Int64.Parse(myOtherVar) == 0 ? null : (long?) Int64.Parse(myOtherVar);
This will work:
..for those who like short answers.
The compiler ignores the left-hand side when figuring out the type of the right-hand side. So when it tries to deduce the type of
it does so without paying any attention to the fact the left-hand side is a
long?
. To determine the type of the right-hand side it notes thatis a
long
and now tries to see ifnull
is or can be implicitly converted to along
. Since it can not, you get the error message that you see.From §7.14 of the C# specification:
Note that we are in situation (2) where
x
isnull
and does not have a type andy
isInt64.Parse(myOtherVar)
and has typelong
. Note thatx
is not implicitly convertible to the type ofy
. Therefore both (1) and (2) fail above and we result in (3) which results in the compile-time error that inspired your question. Note the implicit conclusion from the above that the left-hand side does not play a role in determining the type of right-hand side.To rectify this replace
with
Now, the reason why
is okay where
myVar
is declared aslong?
is because the compiler knows there is an implicit conversion fromnull
tolong?
.Lastly,
Int64.Parse
will throw ifmyOtherVar
can't be parsed to along
. Note that you are also performing the parse twice, which is unnecessary. A better pattern isYour operator usage is returning an
Int64
, not anullable
one, because of the last part of the ternary operator. It may work if you do instead:So that you are returning a
long?
instead, so thenull
doesn't need to be converted toInt64
Also, you are converting the value twice in your code, unnecessarily (once to test, and once to get the value). Your code might be better thus:
I am sure you meant to say:
instead of
I liked the usage of the 'out' variable. Thanks.