Better way to convert an int to a boolean

C#BooleanInt

C# Problem Overview


The input int value only consist out of 1 or 0. I can solve the problem by writing a if else statement.

Isn't there a way to cast the int into a boolean?

C# Solutions


Solution 1 - C#

int i = 0;
bool b = Convert.ToBoolean(i);

Solution 2 - C#

I assume 0 means false (which is the case in a lot of programming languages). That means true is not 0 (some languages use -1 some others use 1; doesn't hurt to be compatible to either). So assuming by "better" you mean less typing, you can just write:

bool boolValue = intValue != 0;

Solution 3 - C#

Joking aside, if you're only expecting your input integer to be a zero or a one, you should really be checking that this is the case.

int yourInteger = whatever;
bool yourBool;
switch (yourInteger)
{
    case 0: yourBool = false; break;
    case 1: yourBool = true;  break;
    default:
        throw new InvalidOperationException("Integer value is not valid");
}

The out-of-the-box Convert won't check this; nor will yourInteger (==|!=) (0|1).

Solution 4 - C#

I think this is easiest way:

int i=0;
bool b=i==1;

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
QuestionDeepSeaView Question on Stackoverflow
Solution 1 - C#EvelieView Answer on Stackoverflow
Solution 2 - C#CorakView Answer on Stackoverflow
Solution 3 - C#RawlingView Answer on Stackoverflow
Solution 4 - C#Stevan DejanovicView Answer on Stackoverflow