For C# 8.0 upwards, the quickest way is to use the binary null-coalescing operator ??
which returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result as follows:
bool? nullable = null;
if(nullable ?? false) return; //if nullable is null, default to false
Depending on what you want to happen if nullable
is null
you put false
or true
on the right hand side of ??
.
See documentation for ??
on MSDN: https://learn.microsoft.com/en-gb/dotnet/csharp/language-reference/operators/null-coalescing-operator
Another option is to use nullable.GetValueOrDefault()
which does not allow one to return true
in case of null
however (thanks user:Magnus)
To work around this caveat, you can first handle the case if nullable is false, then use .GetValueOrDefeault()
knowing that the default will never be used:
if(nullable == null ? false : nullable.GetValueOrDefault()) return;