Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#.net can't assign null to a variable in an inline if statement

Tags:

c#

.net

I was just wondering why the following code doesn't work (please keep in mind that I set age to be nullable):

myEmployee.age = conditionMet ? someNumber : null;

Yet the following works fine:

if(conditionMet)
{
    myEmployee.age = someNumber;
}
else
{
    myEmployee.age = null;
}

Why can't I set the value to null in a conditional operator?? All these if statements in my code is not nice.

Thanks.

like image 388
PaulG Avatar asked Nov 28 '22 14:11

PaulG


1 Answers

The types on both sides have to be the same (or be implicitly convertible):

myEmployee.age = conditionMet ? someNumber : (int?)null;

From the docs:

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.

like image 75
BrokenGlass Avatar answered Dec 17 '22 16:12

BrokenGlass