Null-coalescing operator and operator && in C#

boolean-logic, c#, logical-operators, null-coalescing-operator

Solution

I'm wondering why nobody has suggested this so far:

bool? any = this.ViewState["any"] as bool?;
return any & this.SomeBool;

This returns

- `null` if `any` is null, no matter what the value of `this.SomeBool` is;

- `true` if both `any` and `this.SomeBool` are true; and

- `false` if `any` is not null, and `this.SomeBool` is false.

Problem

Is it possible to use together any way operator `??` and operator `&&` in next case: ``` bool? Any { get { var any = this.ViewState["any"] as bool?; return any.HasValue ? any.Value && this.SomeBool : any; } } ``` This means next: - if `any` is null then `this.Any.HasValue` return `false` - if `any` has value, then it returns value considering another boolean property, i.e. `Any && SomeBool`

Original source

Related problems