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)
...
}
intandboolcan’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
booleanvalue explicitly.It is not possible to write:
Imagine if the developer wanted to compare foo with 20 but missed one equality sign:
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 explicitbreakorreturn.