C#’s bool
type (aliasing the System.Boolean
type) is a logical value that can
be assigned the literal true
or
false
.
Although a Boolean value requires only one bit of storage, the
runtime will use one byte of memory, since this is the minimum chunk that
the runtime and processor can efficiently work with. To avoid
space-inefficiency in the case of arrays, the Framework provides a
BitArray
class in the System.Collections
namespace, designed to use
just one bit per Boolean value.
==
and !=
test for equality and inequality of any type, and always
return a bool
value. Value types
typically have a very simple notion of equality:
int x = 1, y = 2, z = 1; Console.WriteLine (x == y); // False Console.WriteLine (x == z); // True
For reference types, equality, by default, is based on
reference, as opposed to the actual
value of the underlying object. Therefore, two
instances of an object with identical data are not considered equal
unless the ==
operator for that type
is specially overloaded to that effect (see the section The object Type and the section Operator Overloading).
The equality and comparison operators, ==
, !=
, <
,
>
, >=
, and <=
, work for all numeric types, but should
be used with caution with real numbers (see Real Number Rounding Errors in the previous section). The
comparison operators also work on enum
type members, by comparing their
underlying integral values.
The &&
and ||
operators test for and and or conditions. They are frequently used in
conjunction with the !
operator,
which expresses not. In this example, the UseUmbrella
method returns true
if it’s rainy or sunny (to protect us
from the rain or the sun), as long as it’s not also windy (since
umbrellas are useless in the wind):
static bool UseUmbrella (bool rainy, bool sunny, bool windy) { return !windy && (rainy || sunny); }
The &&
and ||
operators short-circuit evaluation when possible. In the
preceding example, if it is windy, the expression (rainy || sunny)
is not even evaluated. Short
circuiting is essential in allowing expressions such as the following to
run without throwing a NullReferenceException
:
if (sb != null && sb.Length > 0) ...
The &
and |
operators also test for
and and or conditions:
return !windy & (rainy | sunny);
The difference is that they do not short-circuit. For this reason, they are rarely used in place of conditional operators.
The ternary conditional operator (simply called the
conditional operator) has the form q ? a : b
, where if condition q
is true, a
is evaluated, else b
is evaluated. For example:
static int Max (int a, int b) { return (a > b) ? a : b; }
The conditional operator is particularly useful in LINQ queries.