Rajarshi
Rajarshi

Reputation: 174

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.

Upvotes: 8

Views: 2150

Answers (5)

Jon Skeet
Jon Skeet

Reputation: 1499770

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.

Upvotes: 21

Stephen Cleary
Stephen Cleary

Reputation: 456322

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.

Upvotes: 1

Marcel
Marcel

Reputation: 8519

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

Upvotes: 1

Mohnkuchenzentrale
Mohnkuchenzentrale

Reputation: 5885

Maybe you could try :

default( int? );

instead of null

Upvotes: 2

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120917

try this:

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

Upvotes: 4

Related Questions