I'm having one null-able bool (bool?
) variable, it holds a value null. One more variable of type pure bool
, I tried to convert the null-able bool to bool. But I faced an error "Nullable object must have a value."
My C# Code is
bool? x = (bool?) null;
bool y = (bool)x;
Unfortunately the compiler is not capable of deducing that the statement boolean var1=(var=null); would always lead to the invalid assignment boolean var1=null .
A bool is literally that - a boolean value. So either 1 or 0 - true or false. In C only pointers can be NULL.
The way you typically represent a “missing” or “invalid” value in C# is to use the “null” value of the type. Every reference type has a “null” value; that is, the reference that does not actually refer to anything.
Nullable boolean can be null, or having a value “true” or “false”.
Use x.GetValueOrDefault()
to assign default value (false
for System.Boolean
) to y
in the event that x.HasValue == false
.
Alternatively you can use the null-coalescing operator (??), like so:
bool y = x ?? false;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With