theknut theknut - 3 months ago 13
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

(bool)intValue
doesn't work. I get an
InvalidCastException
. I know I can use
Convert.ToBoolean(...)
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)
...
}

Answer

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.