20

From the MSDN documentation, the following two snippets are equal:

bool value;
int x = (value) ? 0 : 1;

And

bool value;
int x;
if (value)
    x = 0;
else
    x = 1;

Great, wonderful. I use it all the time. Terse and effective.

If we try this with a nullable type, like so:

int? x = (value.HasValue) ? value.Value : null;

We get a compile-time error:

The type of conditional expression cannot be determined
because there is no implicit conversion between '{NullableType}' and null.

This compiles fine:

int? value;
int? x;

if (value.HasValue)
    x = value.Value;
else
    x = null;

So, I understand that the compiler requires an explicit cast in the way of (int?)null to compile the first statement. What I don't understand is why it is required in that statement, but not the If Else block.

3
  • Possible duplicate: stackoverflow.com/questions/295833/… Commented Sep 12, 2013 at 19:08
  • 1
    @NickGotch I've seen your post, but I'm honestly not satisfied with the answer. I want to understand why the cast is required when using one type of syntax vs the other. Commented Sep 12, 2013 at 19:13
  • 1
    I think in this case you can just do x = value, or am I wrong? Commented Sep 13, 2013 at 6:59

5 Answers 5

27

null can represent any object-based datatype. You need to cast null as a datatype so it know what you are talking about.

int? x = (value.HasValue) ? value.Value : (int?)null;

I know, it sounds a bit strange.


To answer the questions in the comments:

Why is it not implicit though?
Yeah, I get that. But why do I not have to cast it in a If Else block?

Let's walk through the code.

Your else statement looks like this:

else x = null;

This means you are assigning the value of null to x. This is valid, because x is a int?, which takes nulls.

The difference comes when you have the ternary operator. It says: "assign the value of the operator into x". The question (and the reason for your error) is, what datatype is the result of the ternary operator?

From your code, you can't be sure, and the compiler throws its hands up.

int? x = (value.HasValue) ? value.Value : null;
// int?        bool             int        ??

What datatype is null? You are quick to say "well it's a int?, because the other side is a int and the result is a int?". The problem is, what about the following:

string a = null;
bool? b = null;
SqlConnectionStringBuilder s = null;

This is also valid, which means null can be used for any object-based datatype. This is why you have to explicitly cast null as the type you want to use, because it can be used for anything!


Another explanation (and possible more accurate):

You can't have an implicit cast between a nullable and a non-nullable value.

int is not-nullable (it's a structure), where null is. This is why in Habib's answer you can put the cast on either the left or right side.

Sign up to request clarification or add additional context in comments.

4 Comments

Why is it not implicit though?
Yeah, I get that. But why do I not have to cast it in a If Else block?
@gunr2171 Ah ha! Yes, this makes sense now. Just to clarify; the ?: operator expects a single data type for all 3 operands, yes? Or, at least, a convertible type.
@Michael, sort of. The "condition" needs a boolean, to quote msdn: Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other. (null does not have an implicit conversion with others).
11

For Condtional operator MSDN states:

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

So in you case your first_expression and second_expression are:

int? x = (value.HasValue) ? value.Value : null;
                             ^^^^^^^^      ^^^^^
                             first exp     2nd Exp

Now if you see, your First Expression is of type int, and second expression is null and both are not same and there is no implicit conversion. So casting any of them to `int? solves the problem.

So:

int? x = (value.HasValue) ? (int?) value.Value : null;

Or

int? x = (value.HasValue) ? value.Value : (int?) null;

are fine.

Now why it is not required with if-else, because there multiple statements involved and it not a single statement assigning the value.

Comments

6
var x = value.HasValue ? value.Value : default(int?);

works too.

Comments

1

The documentation for the ?: operator states that the type of the expression b ? x : y is determined by examining the types of x and y:

  • If X and Y are the same type, then this is the type of the conditional expression.
  • Otherwise, if an implicit conversion (Section 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 (Section 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.

In your example

int? x = (value.HasValue) ? value.Value : null;

there is no implicit conversion between int and null so the last bullet applies.

1 Comment

I think this is the best answer, although why doesn't the conversion use b to determine type?
0

The reason is that the type of conditional expression is determined by the second and third operators of the conditional operator (?:) .

Since null has no type, the compiler cannot determine the type of the overall expression so it emits a compiler error.

The reason it works with the simple assignment operator (=) is because the left side of the operator determines the the type. Since in the If statement, the type of x is already known, the compiler doesn't complain.

See section 7.14 (Conditional operator) and section 7.17.1 (Simple assignment) for further explanations.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.