user1108948
user1108948

Reputation:

Converting Nullable<bool> to bool

I got this compiler error:

Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?).

for the following code:

 xEnable = was.xEnable;

xEnable is a nullable column in DB.

Upvotes: 0

Views: 2048

Answers (6)

J. Steen
J. Steen

Reputation: 15578

For C# 8.0 and later, you can use the ?? operator, as you asked, and do

xEnable = was.xEnable ?? false;

if you want false to be the default value when was.xEnable is null.

Upvotes: 2

Tigran
Tigran

Reputation: 62248

bool a = false; 
bool? b = null; 
a = (bool)b;

this will raise an exception in case when b is null.

So possible solutions could be:

  • you know that b is never null, so use this pattern (bad)
  • make a nullable too, by bool? a = false;
  • check for null on b, a = (b == null)?false:b.Value;

Hope this helps.

Upvotes: 0

Barry Kaye
Barry Kaye

Reputation: 7761

Are you trying to actually pass a null value to the database? If so:

xEnable = was.xEnable.HasValue ? was.xEnable.Value : DBNull.Value;

Upvotes: 0

Rawling
Rawling

Reputation: 50104

To actually use ?? as in your title, go

xEnable = was.xEnable ?? false;

if you want xEnable to be false if was.xEnable is null, or

xEnable = was.xEnable ?? true;

if you want xEnable to be true if was.xEnable is null.

Upvotes: 4

Adi Lester
Adi Lester

Reputation: 25201

If you know that was.xEnable is not null, you can use

xEnable = was.xEnable.Value

If you want to use a default value when was.xEnable is null, you can do the following

bool defaultValue = false;
xEnable = was.xEnable ?? defaultValue;

Upvotes: 1

Mihai
Mihai

Reputation: 2760

This means that

xEnable is of type bool 

and

was.xEnable is of type bool? (ie: nullable bool)

do something like

xEnable = was.xEnable.HasValue ? was.xEnable.Value : false;

where false is the default value in case was.xEnable == null

EDIT Or if you really want you can user the ?? operator like

xEnable = was.xEnable ?? true;

or

xEnable = was.xEnable ?? false;

Upvotes: 13

Related Questions