Convert Int to Bool in C#
-
Convert Integer to Boolean With the
Convert.ToBoolean()
Method in C -
Convert Integer to Boolean With the
switch()
Statement in C
This tutorial will discuss the methods to convert an integer value to a boolean value in C#.
Convert Integer to Boolean With the Convert.ToBoolean()
Method in C
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#. In C#, the integer value 0
is equivalent to false
in boolean, and the integer value 1
is equivalent to true
in boolean.
using System;
namespace convert_int_to_bool
{
class Program
{
static void Main(string[] args)
{
int i = 1;
bool b = Convert.ToBoolean(i);
Console.WriteLine(b);
}
}
}
Output:
True
In the above code, we converted the integer variable i
with value 1
to the boolean variable b
with value true
with the Convert.ToBoolean(i)
function in C#.
Convert Integer to Boolean With the switch()
Statement in C
We can also use the switch()
statement to achieve the same goal as the previous example. The switch()
statement tests a variable for equality among a list of different values in C#. We can use the integer variable inside the switch()
statement and assign false
to the boolean variable in the case of 0
integer value or assign true
to the boolean value in the case of 1
integer value. The following code example shows us how to convert an integer variable to a boolean variable with the switch()
statement in C#.
using System;
namespace convert_int_to_bool
{
class Program
{
static void Main(string[] args)
{
int i = 1;
bool b;
switch (i)
{
case 0:
b = false;
Console.WriteLine(b);
break;
case 1:
b = true;
Console.WriteLine(b);
break;
}
}
}
}
Output:
True
In the above code, we converted the integer variable i
with value 1
to the boolean variable b
with value true
with the switch(i)
statement in C#.