Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Conditional Operation with Nullable Int

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.

like image 229
Rajarshi Avatar asked May 21 '10 10:05

Rajarshi


2 Answers

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.

like image 117
Jon Skeet Avatar answered Oct 23 '22 19:10

Jon Skeet


try this:

int? nullableIntVal = (this.Policy == null) ? (int?) null : 1; 
like image 45
Klaus Byskov Pedersen Avatar answered Oct 23 '22 18:10

Klaus Byskov Pedersen