Convert Int to Bool in C#

  1. Convert Integer to Boolean With the Convert.ToBoolean() Method in C
  2. 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#.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp Integer

  • Convert Long to Integer in C#
  • Convert Float to Int in C#
  • Related Article - Csharp Bool

  • Convert Int to Hex in C#
  • Random Number in a Range in C#