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) ... }
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#.
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);
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 .
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#)
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With