| title | bool (C# Reference) | ||
|---|---|---|---|
| ms.date | 07/20/2015 | ||
| ms.prod | .net | ||
| ms.technology |
|
||
| ms.topic | article | ||
| f1_keywords |
|
||
| helpviewer_keywords |
|
||
| ms.assetid | 551cfe35-2632-4343-af49-33ad12da08e2 | ||
| caps.latest.revision | 30 | ||
| author | BillWagner | ||
| ms.author | wiwagn |
The bool keyword is an alias of xref:System.Boolean?displayProperty=nameWithType. It is used to declare variables to store the Boolean values, true and false.
Note
If you require a Boolean variable that can also have a value of null, use bool?. For more information, see Nullable Types.
You can assign a Boolean value to a bool variable. You can also assign an expression that evaluates to bool to a bool variable.
[!code-csharpcsrefKeywordsTypes#1]
The default value of a bool variable is false. The default value of a bool? variable is null.
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#:
[!code-csharpcsrefKeywordsTypes#2]
To test a variable of the type int, you have to explicitly compare it to a value, such as zero, as follows:
[!code-csharpcsrefKeywordsTypes#3]
In this example, you enter a character from the keyboard and the program checks if the input character is a letter. If it is a letter, it checks if it is lowercase or uppercase. These checks are performed with the xref:System.Char.IsLetter%2A, and xref:System.Char.IsLower%2A, both of which return the bool type:
[!code-csharpcsrefKeywordsTypes#4]
[!INCLUDECSharplangspec]
C# Reference
C# Programming Guide
C# Keywords
Integral Types Table
Built-In Types Table
Implicit Numeric Conversions Table
Explicit Numeric Conversions Table