Summary: in this tutorial, you’ll learn about the C# bool
type that represents boolean values, true and false.
Introduction to the C# bool type
C# use the bool
keyword to represent the boolean type with two values: true
and false
. A variable of the bool
type can hold one of these two values.
For example, the following declares two variables with the bool
type:
bool canVote = true;
bool open = false;
Code language: C# (cs)
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
:
bool result = 10 > 20;
Console.WriteLine(result);
Code language: C# (cs)
Output:
False
Code language: C# (cs)
Likewise, the following expression uses the ==
operator to compare two strings and returns true
:
bool result = "One" == "One";
Console.WriteLine(result);
Code language: C# (cs)
Output:
True
Code language: C# (cs)
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.
Summary
- Use the
bool
keyword to declare a boolean variable that can hold one of two values: true and false. - The result of expressions that uses comparison or equality operators has the type
bool
.