C# Boolean Variable Type

C# Boolean Variable Type

Only two values are allowed for Boolean literals true and false.

C# use the bool keyword to represent the boolean type with two values: true and false.

For example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            bool x = true;
            bool y = false;
            Console.WriteLine(x);
            Console.WriteLine(y);
            Console.ReadLine();
        }
    }
}

Output:

C# boolean type

Note that the true and false are two boolean literal values.

When comparing two values using the comparison or equality operators, you’ll get a value of the bool type.

For example, the following expression uses the > operator to compare two numbers; The type of the result is bool:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            bool result = 60 > 80;
            Console.WriteLine("60 > 80 :"+result);
            Console.ReadLine();
        }
    }
}

Output:

C# bool keyword

Likewise, the following expression uses the == operator to compare two strings and returns true:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            bool result = "XDevSpace" == "XDevSpace";
            Console.WriteLine(result);
            Console.ReadLine();
        }
    }
}

Output:

C# bool keyword - C# Boolean literals

In practice, you’ll use the boolean values in the if, do, while, and for statement and in the ternary operator ?:.

Technically, the bool type is an alias for the .NET System.Boolean structure type.

Boolean variables are particularly useful in flow control constructs such as if and while statements.

Unlike some other programming languages, C# boolean variables must be assigned either true or false and cannot be assigned 1 or 0.