Skip to content

Latest commit

 

History

History
55 lines (43 loc) · 3.02 KB

File metadata and controls

55 lines (43 loc) · 3.02 KB
title bool (C# Reference)
ms.date 07/20/2015
ms.prod .net
ms.technology
devlang-csharp
ms.topic article
f1_keywords
bool_CSharpKeyword
bool
helpviewer_keywords
bool keyword [C#]
ms.assetid 551cfe35-2632-4343-af49-33ad12da08e2
caps.latest.revision 30
author BillWagner
ms.author wiwagn

bool (C# Reference)

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.

Literals

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.

Conversions

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]

Example

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]

C# Language Specification

[!INCLUDECSharplangspec]

See Also

C# Reference
C# Programming Guide
C# Keywords
Integral Types Table
Built-In Types Table
Implicit Numeric Conversions Table
Explicit Numeric Conversions Table