c# - mvc - html checkboxfor cannot implicitly convert type bool ?' to bool
cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists(are you missing a cast?) (5)
bool? is not a
bool. It is in reality a
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.
IsChecked is null, this line will error.
obj.IsDisplay = (bool) chkDisplay.IsChecked;
Error : cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)
Test obj = new Test(); obj.IsDisplay = chkDisplay.IsChecked;
but when i use this means cast in bool then there is no error.
Test obj = new Test(); obj.IsDisplay = (bool) chkDisplay.IsChecked;
I need to know that, why need to cast this bool to bool.
chkDisplay.IsChecked is of type
bool?. Which means it can hold values
obj.IsDisplay is of type
bool. Which means it can only hold
Hence you have to explicitly cast it to type
bool. However, this will still throw an exception if, the value you are trying to cast to bool is
bool? nullableBool = null; bool notNullableBool = (bool)nullableBool; //This will throw InvalidOperationException
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.IsDisplay = chkDisplay.IsChecked ?? false;
You can use below code
obj.IsDisplay = chkDisplay.IsChecked == true?true:false;
bool is not equals bool?
bool can take two values,
bool? can take three,
true false and
That is why they are different