Why assigning null in ternary operator fails: no implicit conversion between null and int?

前端 未结 5 2013
青春惊慌失措
青春惊慌失措 2020-12-11 16:08

This fails with a There is no implicit conversion between \'null\' and \'int\'

long? myVar = Int64.Parse( myOtherVar) == 0 ? null : Int64.Parse(         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-11 16:12

    The Compiler tries to evaluate the expressions from left to right

    long? myVar = Int64.Parse( myOtherVar) == 0 ? null : Int64.Parse( myOtherVar);
    

    int64.parse method return a long value not a nullable long value. so there is no conversion between null and Int64.Parse( myOtherVar); So, try this one

    long? myVar = Int64.Parse(myOtherVar) == 0 ? (long?) null : Int64.Parse(myOtherVar);
    

    OR
    long? myVar = Int64.Parse(myOtherVar) == 0 ? null : (long?) Int64.Parse(myOtherVar);

提交回复
热议问题