0

Hello is there any way formulate a condition like the one below ? If field is null then false else field.Property ?

class Node
{
    public bool IsFilled;
}

class Holder
{
    Node nodeBuffer;
    public bool IsFilled => this.nodeBuffer?.IsFilled ?? false; 
}

How can i say something like if nodeBuffer is null then false else nodeBuffer.IsFilled?

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
Bercovici Adrian
  • 8,794
  • 17
  • 73
  • 152

2 Answers2

7

Yes, you can use the equality operator which works with Nullable<bool>

public bool IsFilled => this.nodeBuffer?.IsFilled == true;

Nullable types support all operators that their non-nullable type support, that's called: lifted operator

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

this.nodeBuffer?.IsFilled returns a Nullable<T> so you can just use GetValueOrDefault() method on it so it will be false if null.

So your property definition will look like below:

public bool IsFilled => (this.nodeBuffer?.IsFilled).GetValueOrDefault();
CodeNotFound
  • 22,153
  • 10
  • 68
  • 69