J4N
J4N

Reputation: 20717

Why ?: operator does not work with nullable<int> assignation?

I'm creating an object for my database and I found a weird thing, which I don't understand:

I've an object which should reference a "language" by an ID, but this can be null, so my property is a int?(Nullable<int>)

so firstly I tried to use the object initializer:

myObject = new MyObject() 
{
    myNullableProperty = language == null ? null : language.id;
}

but it doesn't work! It tell me that null cannot be converted to int

But if I it in a if/else structure, I can put null in a var and then assign it to my properties.

Why is this acting like this?

Upvotes: 2

Views: 148

Answers (4)

Piotr Auguscik
Piotr Auguscik

Reputation: 3681

Most likely null is interpreted as object which obviously can't be assigned to int. You might want to use myNullableProperty = language == null ? (int?)null : language.id;

Upvotes: 0

Christoph Fink
Christoph Fink

Reputation: 23103

The reason is, when using the ? operator the left and the right side of the : are required to be from the same type and typeof(null)!=typeof(int) so:

myNullableProperty = language == null ? (int?)null : language.id;

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038820

You may try casting the null to int? as the ?: operator requires both operands to return the same type:

myNullableProperty = language == null ? (int?)null : language.id

Upvotes: 9

schglurps
schglurps

Reputation: 1387

This is because of a type mismatch. You must cast your null value to the int type.

Upvotes: 0

Related Questions