Reputation:
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
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
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:
b
is never null
, so use this pattern (bad) a
nullable too, by bool? a = false
;null
on b
, a = (b == null)?false:b.Value;
Hope this helps.
Upvotes: 0
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
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
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
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