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 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.

Equality and Comparison Operators

== 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.

Conditional Operators

The && and || operators test for and

Get C# 4.0 Pocket Reference, 3rd 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.