Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
bool
Collapse the table of content
Expand the table of content

bool (C# Reference)

The bool keyword is an alias of System.Boolean. It is used to declare variables to store the Boolean values, true and false.

NoteNote

If you require a Boolean variable that can also have a value of null, use bool. For more information, see Nullable Types (C# Programming Guide).

You can assign a Boolean value to a bool variable. You can also assign an expression that evaluates to bool to a bool variable.

// keyword_bool.cs
using System;
public class MyClass
{
    static void Main()
    {
        bool i = true;
        char c = '0';
        Console.WriteLine(i);
        i = false;
        Console.WriteLine(i);

        bool Alphabetic = (c > 64 && c < 123);
        Console.WriteLine(Alphabetic);
    }
}

Output

 
True
False
False

In C++, a value of type bool can be converted to a value of type int; in other words, false is equivalent to zero and true is equivalent to nonzero values. In C#, there is no conversion between the bool type and other types. For example, the following if statement is invalid in C#, while it is legal in C++:

int x = 123;
if (x)   // Invalid in C#
{
    printf_s("The value of x is nonzero.");
}

To test a variable of the type int, you have to explicitly compare it to a value, such as zero, as follows:

int x = 123;
if (x != 0)   // The C# way
{
    Console.Write("The value of x is nonzero.");
}

In this example, you enter a character from the keyboard and the program checks if the input character is a letter. If so, it checks if it is lowercase or uppercase. These checks are performed with the IsLetter, and IsLower, both of which return the bool type:

// keyword_bool_2.cs
using System;
public class BoolTest 
{
    static void Main() 
    {
        Console.Write("Enter a character: "); 
        char c = (char)Console.Read();
        if (Char.IsLetter(c))
        {
            if (Char.IsLower(c))
            {
                Console.WriteLine("The character is lowercase.");
            }
            else
            {
                Console.WriteLine("The character is uppercase.");
            }
        }
        else
        {
            Console.WriteLine("Not an alphabetic character.");
        }
    }
}

Input

 
X

Sample Output

 
Enter a character: X
The character is uppercase.
Additional sample runs might look as follow:
Enter a character: x
The character is lowercase.

Enter a character: 2
The character is not an alphabetic character.

For more information on bool and related subjects, see the following sections in the C# Language Specification:

  • 4.1.8 The bool Type

  • 7.9.4 Boolean Equality Operators

  • 7.11.1 Boolean Conditional Logical Operators

Community Additions

ADD
Show:
© 2015 Microsoft