C# - Boolean data type

In C#, the boolean data type is used to represent true or false values, and it's one of the fundamental data types. It's often used for making decisions or performing conditional operations in your code. A boolean variable can only have two values: true or false, which represent the concept of "yes" or "no," "on" or "off," or "1" or "0."

Here's a simple explanation with a code example that illustrates the boolean data type:


using System;

class Program
{
    static void Main()
    {
        // Declare boolean variables
        bool isRaining = true;
        bool isSunny = false;

        // Use boolean variables in conditional statements
        if (isRaining)
        {
            Console.WriteLine("Grab an umbrella!");
        }
        else
        {
            Console.WriteLine("Enjoy the weather!");
        }

        if (isSunny)
        {
            Console.WriteLine("Don't forget your sunscreen!");
        }
        else
        {
            Console.WriteLine("No need for sunscreen today.");
        }
    }
}

Explanation of the code:

  • In this example, we declare two boolean variables: isRaining and isSunny.
  • We use these boolean variables in conditional statements (if and else) to make decisions based on their values.
  • Depending on whether isRaining or isSunny is true or false, we print different messages to the console.

Expected Output:


Grab an umbrella!
No need for sunscreen today.

In this output, the program provides different messages based on the boolean values. If isRaining is true, it advises you to grab an umbrella, and if isSunny is false, it tells you that there's no need for sunscreen.