C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Info: The word bool comes from George Boole, a mathematician who pioneered Boolean logic in the 1800s in England.
C# program that uses bool
using System;
class Program
{
static void Main()
{
bool val = true;
if (val)
{
Console.WriteLine(val == true);
}
val = !val;
if (!val)
{
Console.WriteLine(val == false);
}
}
}
Output
True
True
Part 1: We set the bool to true. Then we set the variable value equal to its opposite value.
Part 2: If-statements can test a bool. In an if-statement, the expression is evaluated in a Boolean context.
Part 3: We can store the result of an expression evaluation as a local variable. This technique can simplify complex logic tests.
Part 4: We print some details of the bool type, including its size in bytes and its Type representation.
C# program that uses bool in many contexts
using System;
class Program
{
static void Main()
{
// Part 1: set values to bool.
bool value = true;
Console.WriteLine(value);
value = !value;
Console.WriteLine(value);
value = false;
Console.WriteLine(value);
// Part 2: use if-statements with bool.
if (value)
{
Console.WriteLine("Not reached");
}
if (!value)
{
Console.WriteLine("Reached");
}
// Part 3: use a bool local to store an expression result.
bool test = !value &&
1 == int.Parse("1");
Console.WriteLine(test);
// Part 4: print bool details.
Console.WriteLine(sizeof(bool));
Console.WriteLine(true.GetType());
}
}
Output
True
False
False
Reached
True
1
System.Boolean
Here: This program uses the Convert type to convert ints into bools. The Convert.ToBoolean method is perfect for this purpose.
Info: This method considers 0 to be false. All other values, positive and negative, are true.
C# program that converts int to bool
using System;
class Program
{
static void Main()
{
Console.WriteLine(Convert.ToBoolean(5));
Console.WriteLine(Convert.ToBoolean(0));
Console.WriteLine(Convert.ToBoolean(-1));
}
}
Output
True
False
True
Initialized: The null value of a nullable bool can be used to mean uninitialized. So we can have a 3-state bool here.
NullableC# program that uses nullable bool
using System;
class Program
{
static void Main()
{
// A null bool can mean an uninitialized boolean value.
bool? valid = null;
Console.WriteLine("Initialized: {0}", valid.HasValue);
// We can then set the nullable bool to true or false.
valid = true;
Console.WriteLine("Valid: {0}", valid.Value);
}
}
Output
Initialized: False
Valid: True
Methods: In C# programs, methods often return bool values. These methods sometimes have the prefix "Is" on their names.
bool: ReturnAlso: Properties can return bool values. The book Code Complete shows how boolean expressions are simplified.
Quote: A CLI Boolean type occupies 1 byte in memory. A bit pattern of all zeros denotes a value of false. A bit pattern with any bit set (analogous to a non-zero integer) denotes a value of true (The CLI Annotated Standard).