ערוך

שתף באמצעות


bool (C# reference)

The bool type keyword is an alias for the .NET System.Boolean structure type that represents a Boolean value, which can be either true or false.

To perform logical operations with values of the bool type, use Boolean logical operators. The bool type is the result type of comparison and equality operators. A bool expression can be a controlling conditional expression in the if, do, while, and for statements and in the conditional operator ?:.

The default value of the bool type is false.

Literals

You can use the true and false literals to initialize a bool variable or to pass a bool value:

bool check = true;
Console.WriteLine(check ? "Checked" : "Not checked");  // output: Checked

Console.WriteLine(false ? "Checked" : "Not checked");  // output: Not checked

Three-valued Boolean logic

Use the nullable bool? type, if you need to support the three-valued logic, for example, when you work with databases that support a three-valued Boolean type. For the bool? operands, the predefined & and | operators support the three-valued logic. For more information, see the Nullable Boolean logical operators section of the Boolean logical operators article.

For more information about nullable value types, see Nullable value types.

Conversions

C# provides only two conversions that involve the bool type. Those are an implicit conversion to the corresponding nullable bool? type and an explicit conversion from the bool? type. However, .NET provides additional methods that you can use to convert to or from the bool type. For more information, see the Converting to and from Boolean values section of the System.Boolean API reference page.

C# language specification

For more information, see The bool type section of the C# language specification.

See also