C # .net cannot set null to inline if variable

I'm just wondering why the following code does not work (remember what I set ageto nullable):

myEmployee.age = conditionMet ? someNumber : null;

However, the following works just fine:

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

Why can't I set null in a conditional statement? All of these instructions ifin my code are not very pleasant.

Thank.

+3
source share
4 answers

Types on both sides must be the same (or be implicitly convertible):

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

From docs :

Any type of expression first_expression and second_expression must be the same, or an implicit conversion must exist from one type to another.

+14
source

, null :

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

, :

[MSDN] nullable HasValue false. undefined.

null. , :

if (conditionMet)
    myEmployee.age = someNumber;

.


null , - , :

myEmployee.age = null;

if (conditionMet)
    myEmployee.age = someNumber;
+2

. int null . , age a Nullable<int> ( int?) someNumber int?.

, : null . , null . , , , .

0

All Articles