简体   繁体   中英

Is there a reason C# doesn't support short-hand, null-conditional checking in logical evaluations?

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?

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 someInstance?.SomeBooleanProperty ?? false would satisfy both conditions. ?. alone cannot / shoudn't infer this logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM