• Register
100 points
2
In this code example, I will convert Bool to Int in the programming language C# - this article will give you a thorough guide on how to do it perfectly, without any errors in the output of the code.

In most programming languages, a bool can be converted to 0 or 1, whereby false is equivalent to 0 and true is equivalent to 1. Converting Bool to Int in C# can't be done implicitly. When you try converting Bool to Int in C# an error "Cannot convert type bool to int" will occur in the program. This error occurs because in C# the compiler is making sure the program is perfectly correct.

But you can use Convert.ToInt32(bool) Method, to convert a specific Boolean(bool) value to an integer (int 32 signed number) - which is an equivalent value to Boolean(bool).

Code example;

using System;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Convert.ToInt32(true) : " + Convert.ToInt32(true));
            Console.WriteLine("Convert.ToInt32(false): " + Convert.ToInt32(false));

            bool a = true;
            bool b = false;

            Console.WriteLine("Convert.ToInt32(a) : " + Convert.ToInt32(a));
            Console.WriteLine("Convert.ToInt32(b): " + Convert.ToInt32(b));

            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output;

Convert.ToInt32(true) : 1
Convert.ToInt32(false): 0
Convert.ToInt32(a) : 1
Convert.ToInt32(b): 0
100 points
2