Operators and Expressions
Boolean Logical Operators
Unary
!
(logical negation) operator.Binary
&
(logicalAND
),|
(logicalOR
), and^
(logical exclusiveOR
) operators. Those operators always evaluate both operands.Binary
&&
(conditional logicalAND
) and||
(conditional logicalOR
) operators. Those operators evaluate the right-hand operand only if it's necessary.
Logical negation operator !
bool passed = false;
Console.WriteLine(!passed); // output: True
Console.WriteLine(!true); // output: False
Logical AND operator &
bool SecondOperand()
{
Console.WriteLine("Second operand is evaluated.");
return true;
}
bool a = false & SecondOperand();
Console.WriteLine(a);
// Output:
// Second operand is evaluated.
// False
bool b = true & SecondOperand();
Console.WriteLine(b);
// Output:
// Second operand is evaluated.
// True
Logical OR operator |
bool SecondOperand()
{
Console.WriteLine("Second operand is evaluated.");
return true;
}
bool a = true | SecondOperand();
Console.WriteLine(a);
// Output:
// Second operand is evaluated.
// True
bool b = false | SecondOperand();
Console.WriteLine(b);
// Output:
// Second operand is evaluated.
// True
x
y
x&y
x|y
true
true
true
true
true
false
false
true
true
null
null
true
false
true
false
true
false
false
false
false
false
null
false
null
null
true
null
true
null
false
false
null
null
null
null
null
Logical exclusive OR operator ^
Console.WriteLine(false ^ false); // output: False
Console.WriteLine(false ^ true); // output: True
Console.WriteLine(true ^ false); // output: True
Console.WriteLine(true ^ true); // output: False
Conditional logical AND operator &&
bool SecondOperand()
{
Console.WriteLine("Second operand is evaluated.");
return true;
}
bool a = false && SecondOperand();
Console.WriteLine(a);
// Output:
// False
bool b = true && SecondOperand();
Console.WriteLine(b);
// Output:
// Second operand is evaluated.
// True
Conditional logical OR operator ||
bool SecondOperand()
{
Console.WriteLine("Second operand is evaluated.");
return true;
}
bool a = true || SecondOperand();
Console.WriteLine(a);
// Output:
// True
bool b = false || SecondOperand();
Console.WriteLine(b);
// Output:
// Second operand is evaluated.
// True
Operator Precedence
!
> &
> ^
> |
> &&
> ||
null-coalescing operators (?? and ??=)
Last updated
Was this helpful?