Reputation: 2923
I'm often finding myself writing code that checks for null
prior to checking a property for a value. The simplest form of this would be:
if (someInstance != null && someInstance.SomeBooleanProperty)
Is there a reason we can't use the null-conditional operator (?.
) to simplify that check if the property following it is a boolean like this?
if (someInstance?.SomeBooleanProperty)
The above example won't compile because it evaluates to null
, not to true
or false
, hence you get an error saying there's no implicit cast available for bool?
to bool
.
We could always cast, or directly check for a value, such as:
if (someInstance?.SomeBooleanProperty == false)
That works fine, and in all honesty, it's not exactly that much extra code. Just, in my opninion here, with all of the simplifications C# has introduced over the years, I can't help but wonder if there is a reason we still can't utilize a shorthand null conditional like this?
Upvotes: 0
Views: 129
Reputation: 539
I think the inherent problem with just using a ?.
alone is what does the condition evaluate to when someInstance
is null. This is why the compiler complains and why you need the null check condition and the non null boolean evaluation. The someInstance?.SomeBooleanProperty ?? false
would satisfy both conditions. ?.
alone cannot / shoudn't infer this logic.
Upvotes: 3