The &&
and ||
operators test for and
and or
conditions.
!
operator expresses not.
The following code creates a boolean expression with and
,
not
and or
operators.
!cloudy && (WeekDay || ThanksGiving);
The &&
and ||
operators short-circuit evaluation when possible.
In the preceding example, if it is cloudy, the expression (WeekDay || ThanksGiving) is not even evaluated.
Short-circuiting allows the following expressions to run without
throwing a NullReferenceException
:
if (reference != null && reference.Length > 0) ...
The &
and |
operators
also test for and
and or
conditions:
return !cloudy & (WeekDay | ThanksGiving);
&
and |
operators do not short-circuit.
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;
}