Can't cast int to bool

Viewed 90591

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)
   ...
}
11 Answers

If all you want is not to have to type the != 0 in if (foo != 0), you could make an extension method for the int type and do something like if (foo.IsNonZero()).

If C# allowed for extension properties, you would be able to write if (foo.IsNonZero) without the parentheses, which in my opinion would read more clearly than the original if (foo != 0), but sadly, that is currently not the case.

You're probably better off with the previously suggested Convert.ToBoolean(foo) either way, though.

Related