Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Type Cast null as Bool in C#?

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;
like image 685
B.Balamanigandan Avatar asked Jan 04 '16 05:01

B.Balamanigandan


People also ask

Can null be cast to boolean?

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 .

Can you set a bool to null in C?

A bool is literally that - a boolean value. So either 1 or 0 - true or false. In C only pointers can be NULL.

IS null boolean false C#?

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.

Can boolean be null in C++?

Nullable boolean can be null, or having a value “true” or “false”.


1 Answers

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;
like image 132
Kirill Shlenskiy Avatar answered Sep 18 '22 19:09

Kirill Shlenskiy