Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)    ... } 
like image 234
theknut Avatar asked Jul 04 '11 12:07

theknut


People also ask

Can you Convert an int to a bool?

Since both integer and boolean are base data types, we can convert an integer value to a boolean value using the Convert class. The Convert. ToBoolean() method converts an integer value to a boolean value in C#.

How to Convert to bool in c#?

OP, you can convert a string to type Boolean by using any of the methods stated below: string sample = "True"; bool myBool = bool. Parse(sample); // Or bool myBool = Convert. ToBoolean(sample);

How do you convert int to boolean in Python?

Integers and floating point numbers can be converted to the boolean data type using Python's bool() function. An int, float or complex number set to zero returns False . An integer, float or complex number set to any other number, positive or negative, returns True .


2 Answers

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#)

like image 191
Ritch Melton Avatar answered Sep 22 '22 23:09

Ritch Melton


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.

like image 28
Jakub Konecki Avatar answered Sep 22 '22 23:09

Jakub Konecki