Can't cast int to bool

C#CastingIntBoolean

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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.

Solution 3 - C#

bool b = Convert.ToBoolean(0);

Will convert 0 and null to false and anything else to true.

Solution 4 - C#

"In other languages, false is equivalent to 0 and true is equivalent to 1, but this is not possible in the C# language."

I have to admit I thought false was zero and true was !false....

int fred = 2;

if (fred == true)
{
    printf("fred is true");
}

will certainly print fred is true

Solution 5 - C#

In other languages, false is equivalent to 0 and true is equivalent to 1, but this is not possible in the C# language.

Solution 6 - C#

In C#, bool is actually a Boolean struct, so it's not just represented as a 1 or 0 internally. It seems like the creators of the language went for an explicit over implicit approach overall with the language. To accomplish what you're trying to do (to effectively cast 1 to true and 0 to false), do this:

if (intValue == 1) {
    // do something
} else if (intValue == 0) {
    // do something else
} else {
    // invalid bool
}

You could also drop the last else clause and do the typical C-language thing and let intValue == 0 be equivalent to false and anything else is true.

Solution 7 - C#

Probably repeating others here but you cant cast int to bool because int is not a bool. It is an int. Who would have thought? ;-)

You need to create a new bool based on your int value, and the already posted "myvar != 0" seems good enough.

Also where do you get your exception? Running the following code will most certainly produce a compiler error:

int myIntValue = 0;
bool myBoolValue = (bool)myIntValue;

You must be doing some generic stuff which is not shown in your question.

Solution 8 - C#

if you want to cast two values variable into bool like var that holds (1 and 2 and want to return 1 for false and 2 for true ) i suggest :

//in the end of method or something :
return w == 2;

Solution 9 - C#

You could use the ternary operator like below, instead of a cast. bool b = true; int i = 1;

// bool to int
i = b == true ? 1 : 0;
// int to bool
b = i > 0 ? true : false;

Solution 10 - C#

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.

Solution 11 - C#

I'm working on a pathfinding, for learning purposes. I need to randomly block some nodes as walkable/blocked.

Here's a simple solution I came up with:

int block = Random.Range(0, 10) + 1;
node.blocked = (block % 2 == 0) ? true : false;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontheknutView Question on Stackoverflow
Solution 1 - C#Ritch MeltonView Answer on Stackoverflow
Solution 2 - C#Jakub KoneckiView Answer on Stackoverflow
Solution 3 - C#kravits88View Answer on Stackoverflow
Solution 4 - C#DaveView Answer on Stackoverflow
Solution 5 - C#Jacob SeleznevView Answer on Stackoverflow
Solution 6 - C#FishBasketGordoView Answer on Stackoverflow
Solution 7 - C#user604613View Answer on Stackoverflow
Solution 8 - C#Hany HassanView Answer on Stackoverflow
Solution 9 - C#MuflixView Answer on Stackoverflow
Solution 10 - C#DhiView Answer on Stackoverflow
Solution 11 - C#Artorias2718View Answer on Stackoverflow