Loren Pechtel
Loren Pechtel

Reputation: 9093

Null conditional result type, am I missing something?

if (Station?.SeparateJob) gets flagged and I'm not understanding why.

Resharper is happy with if (Station?.SeparateJob == true) and normally it would flag the == true.

I thought null was supposed to evaluate to false in this situation but I'm being told I can't cast a nullable to bool like this.

Upvotes: 2

Views: 41

Answers (1)

BJ Myers
BJ Myers

Reputation: 6823

C# does not allow coercion of null to false, nor the coercion of nullable types to their non-nullable counterparts.

Station?.SeparateJob evaluates to a bool?. (It has to, because if Station is null, then the result is null.) An if statement cannot be performed on a bool?, and a bool? cannot be implicitly converted to a bool, so the compiler emits an error.

However, the statement Station?.SeparateJob == true is allowed, since nullable types can be compared to their non-nullable counterparts. This comparison returns true if the left side is true, and false if the left side is false or null. The result of the comparison is a true bool (not nullable), so the if statement compiles.

Resharper will flag cases where you compare a bool to true (since it's unnecessary), but does not flag cases where you compare a bool? to true (because it is required).

Upvotes: 3

Related Questions