Reputation: 7102
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.
Upvotes: 5
Views: 4972
Reputation: 12348
Look at what the documentation has to say:
[MSDN] The default value for a nullable type variable sets HasValue to false. The Value is undefined.
The default is thus null
. Which means that you can simply do:
if (conditionMet)
myEmployee.age = someNumber;
There is no need for more obscure code syntax.
If required you can initialize it with null
in advance, if it somehow was not the default, like so:
myEmployee.age = null;
if (conditionMet)
myEmployee.age = someNumber;
Upvotes: 2
Reputation: 10961
The types of the parts of the ternary statement must be implicitly castable to a common base. In the case of int
and null
, they aren't. You can solve this by making age
a Nullable<int>
(or int?
) and casting someNumber
to int?
.
EDIT to clarify: you can set the value to null
with a ternary statement with proper casting. The problem here isn't that you're trying to set a value to null
with a ternary statement. It's that the compiler-inferred return types of the two expressions involved in the ternary statement cannot be implicitly casted to a common base type.
Upvotes: 0
Reputation: 171411
You can, just be clear about the type that null
should be interpreted as:
myEmployee.age = conditionMet ? someNumber : (int?)null;
Upvotes: 8
Reputation: 160902
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.
Upvotes: 19