How to use Conditional Operation with Nullable Int

我只是一个虾纸丫 提交于 2019-12-04 20:10:25

问题


A small problem. Any idea guys why this does not work?

int? nullableIntVal = (this.Policy == null) ? null : 1;

I am trying to return null if the left hand expression is True, else 1. Seems simple but gives compilation error.

Type of conditional expression cannot be determined because there is no implicit conversion between null and int.

If I replace the null in ? null : 1 with any valid int, then there is no problem.


回答1:


Yes - the compiler can't find an appropriate type for the conditional expression. Ignore the fact that you're assigning it to an int? - the compiler doesn't use that information. So the expression is:

(this.Policy == null) ? null : 1;

What's the type of this expression? The language specification states that it has to be either the type of the second operand or that of the third operand. null has no type, so it would have to be int (the type of the third operand) - but there's no conversion from null to int, so it fails.

Cast either of the operands to int? and it will work, or use another way of expessing the null value - so any of these:

(this.Policy == null) ? (int?) null : 1;

(this.Policy == null) ? null : (int?) 1;

(this.Policy == null) ? default(int?) : 1;

(this.Policy == null) ? new int?() : 1;

I agree it's a slight pain that you have to do this.


From the C# 3.0 language specification section 7.13:

The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,

  • If X and Y are the same type, then this is the type of the conditional expression.

  • Otherwise, if an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.

  • Otherwise, if an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression.

  • Otherwise, no expression type can be determined, and a compile-time error occurs.




回答2:


try this:

int? nullableIntVal = (this.Policy == null) ? (int?) null : 1; 



回答3:


Maybe you could try :

default( int? );

instead of null




回答4:


int? i = (true ? new int?() : 1);




回答5:


This works: int? nullableIntVal = (this.Policy == null) ? null : (int?)1;.

Reason (copied from comment):

The error message is because the two branches of the ?: operator (null and 1) don't have a compatible type. The branches of the new solution (using null and (int?)1) do.



来源:https://stackoverflow.com/questions/2881364/how-to-use-conditional-operation-with-nullable-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!