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 (zero or one) of storage, the runtime
will use one or two bytes of memory, as 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, which is designed to use just one bit per Boolean value.
= = and != test for
equality and inequality of any type, but 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:
public class Dude { public string Name; public Dude (string n) { Name = n; } } Dude d1 = new Dude ("John"); Dude d2 = new Dude ("John"); Console.WriteLine (d1 == d2); // False Dude d3 = d1; Console.WriteLine (d1 == d3); // True
The comparison operators, <, >, <=, and
>=, work for all numeric types, but should be used with caution with real numbers (see
the previous section “Real Number Rounding Errors”). The comparison operators also work on enum
type members, by comparing their underlying integral
values.
We’ll explain the equality and comparison operators in greater detail, later, in the “The object Type” and “Operator Overloading” sections.
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 Use Umbrella
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 (as umbrellas are useless in the wind):
static bool UseUmbrella (bool rainy, bool sunny, bool windy) { return ! windy && (rainy || sunny); }
Conditional
operators
short-circuit evaluation when possible. In the preceding example, if it is windy, the expression
(rainy || sunny)
is not even evaluated.
The & and | operators can be used in a similar manner:
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 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; }