Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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

Code :

Test obj = new Test();
obj.IsDisplay = chkDisplay.IsChecked;

but when I use this method to cast the property into a bool then there is no error.

Test obj = new Test();
obj.IsDisplay = (bool) chkDisplay.IsChecked;

I would like to know why I need to cast this bool to bool?

like image 504
Ankit Jain Avatar asked Mar 27 '14 06:03

Ankit Jain


4 Answers

As the others stated bool? is not equal to bool. bool? can also be null, see Nullable<t> (msdn).

If you know what the null state wants to imply, you easily can use the ?? - null-coalescing operator (msdn) to convert your bool? to bool without any side effects (Exception).

Example:

//Let´s say "chkDisplay.IsChecked = null" has the same meaning as "chkDisplay.IsChecked = false" for you
//Let "check" be the value of "chkDisplay.IsChecked", unless "chkDisplay.IsChecked" is null, in which case "check = false"

bool check = chkDisplay.IsChecked ?? false;
like image 95
Sigma Bear Avatar answered Nov 12 '22 03:11

Sigma Bear


You've declared IsChecked as a bool? (Nullable<bool>). A nullable boolean can be either true, false or null. Now ask yourself: If IsChecked was null, then what value should be assigned to IsDisplay (which can only take a true or false)? The answer is that there is no correct answer. An implicit cast here could only produce hidden trouble, which is why the designers decided to only allow an explicit conversion and not an implicit one.

like image 34
Nikola Dimitroff Avatar answered Nov 12 '22 02:11

Nikola Dimitroff


I'm facing your question when I'm using the null check operator ?.:

if (!RolesList?.Any()) //Not accepted: cannot convert bool? to bool

So I'm using this instead

if (RolesList?.Any() != true)
  //value is null or false

In your case you should set it like so:

obj.IsVisible = chkDisplayStuff.IsChecked ?? false;
like image 34
Shimmy Weitzhandler Avatar answered Nov 12 '22 03:11

Shimmy Weitzhandler


bool? is not a bool. It is in reality a Nullable<bool> http://msdn.microsoft.com/en-us/library/b3h38hb0(v=vs.110).aspx

If you need the bool value then you should either cast like you are doing or call the .Value property on the bool?. There is also a .HasValue property you can check to make sure that it is not null.

If IsChecked is null, this line will error.

obj.IsDisplay = (bool) chkDisplay.IsChecked;
like image 16
TyCobb Avatar answered Nov 12 '22 03:11

TyCobb