theknut theknut - 7 months ago 43
C# Question

Can't cast int to bool

I'm facing the problem that C# in my case can't cast the number 1 to bool. In my scenario

doesn't work. I get an
. I know I can use
but I'm just wondering it doesn't work. Any explanation for this?

My code is

if (actualValueType.Name == "Boolean" || setValueType.Name == "Boolean")
if ((bool)actualValue != (bool)setValue)


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.