Boolean Type and Operators
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.
Equality and Comparison Operators
= = 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 ...
Get C# 3.0 Pocket Reference, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.