Can't cast int to bool
Solution 1:
There's no need to cast:
bool result = intValue == 1;
From the docs:
The inclusion of bool makes it easier to write self-documenting code
a bool value is either true or false
1.2.1 Predefined Types (C#)
Solution 2:
int
and bool
can't be converted implicitly (in contrast to C++, for example).
It was a concious decision made by language designers in order to save code from errors when a number was used in a condition. Conditions need to take a boolean
value explicitly.
It is not possible to write:
int foo = 10;
if(foo) {
// Do something
}
Imagine if the developer wanted to compare foo with 20 but missed one equality sign:
if(foo = 20) {
// Do something
}
The above code will compile and work - and the side-effects may not be very obvious.
Similar improvements were done to switch
: you cannot fall from one case to the other - you need an explicit break
or return
.
Solution 3:
bool b = Convert.ToBoolean(0);
Will convert 0 and null to false and anything else to true.