Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler Error for Nullable Bool

Tags:

c#

 bool? ispurchased = null;
    var pospurcahsed= ispurchased ? "1":"2";

Its generating exception .

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

What I am doing wrong here? thanks for your support and consideration.

like image 228
Andrew Avatar asked Dec 16 '22 10:12

Andrew


1 Answers

This is not allows because it is unclear what null means in the context of a conditional.

Nullable Booleans can be cast to a bool explicitly in order to be used in a conditional, but if the object has a value if null, InvalidOperationException will be thrown.

It is therefore important to check the HasValue property before casting to bool.

Use like

   var pospurcahsed=  (ispurchased.HasValue && ispurchased.Value) ?......

Nullable Booleans are similar to the Boolean variable type used in SQL. To ensure that the results produced by the & and | operators are consistent with SQL's three-valued Boolean type, the following predefined operators are provided:

bool? operator &(bool? x, bool? y)

bool? operator |(bool? x, bool? y)

enter image description here

or you can use martin suggestion GetValueOrDefault[Thanks to martin to pointing it out ]

The GetValueOrDefault method returns a value even if the HasValue property is false (unlike the Value property, which throws an exception).

like image 115
joshua Avatar answered Dec 28 '22 19:12

joshua