csharp-operadores-logicos

Logical operators in C#

  • 4 min

Logical operators are special symbols that allow us to combine conditions and perform operations based on the result of those conditions.

The most common logical operators in C# are:

OperatorNameDescription
&&ANDReturns true if both operands are true
||ORReturns true if at least one operand is true
!NOTNegates the value

If you want to learn more, check out the Introduction to Programming Course

List of Logical Operators

Logical AND (&&)

The logical AND operator allows us to evaluate two conditions and returns true if both conditions are true, or false otherwise. For example:

bool condition1 = true;
bool condition2 = false;
bool result = condition1 && condition2; // result will be false
Copied!

Logical OR (||)

The logical OR operator allows us to evaluate two conditions and returns true if at least one of the conditions is true, or false otherwise. For example:

bool condition1 = true;
bool condition2 = false;
bool result = condition1 || condition2; // result will be true
Copied!

Logical NOT (!)

The logical NOT operator allows us to invert the value of a condition. If the condition is true, it returns false, and if the condition is false, it returns true. For example:

bool condition = true;
bool result = !condition; // result will be false
Copied!

Usage Examples

Combining Logical Operators

It is possible to combine several logical operators in a single expression to create more complex conditions. For example:

int number = 15;

bool isMultipleOf3 = (number % 3 == 0);
bool isMultipleOf5 = (number % 5 == 0);

bool isMultipleOf3_or_5 = isMultipleOf3 || isMultipleOf5; // true, since 15 is a multiple of 3
bool isMultipleOf3_and_5 = isMultipleOf3 && isMultipleOf5; // false, since 15 is not a multiple of both 3 and 5
bool isNotMultipleOf3 = !isMultipleOf3; // false
Copied!

Precedence of Logical Operators

When multiple logical operators are combined in an expression, it is important to understand their precedence to evaluate the expression correctly.

The precedence of logical operators in C# follows this order:

  1. ! (NOT)
  2. && (AND)
  3. || (OR)

Therefore, in an expression with && and ||, && is evaluated before ||. However, it is not advisable to rely heavily on this when writing code. Don’t hesitate to use parentheses if it improves readability.

For example:

int a = 5;
int b = 10;
int c = 15;

bool result = (a > b) || (b < c) && (a == c); // true
// Evaluated as: (a > b) || ((b < c) && (a == c))
Copied!

To improve clarity, it is sometimes helpful to use parentheses even when they are not strictly necessary, if it improves readability.

bool result = (a > b) || ((b < c) && (a == c)); // true
Copied!