Convert nullable bool? to bool

KentZhou picture KentZhou · May 20, 2011 · Viewed 107k times · Source

How do you convert a nullable bool? to bool in C#?

I have tried x.Value or x.HasValue ...

Answer

Ken Pespisa picture Ken Pespisa · May 20, 2011

You ultimately have to decide what the null bool will represent. If null should be false, you can do this:

bool newBool = x.HasValue ? x.Value : false;

Or:

bool newBool = x.HasValue && x.Value;

Or:

bool newBool = x ?? false;