Language: EN

csharp-operadores-comparacion

Comparison Operators in C#

Comparison operators allow us to compare two values and determine if they are equal, different, greater, less, greater/equal, or less/equal.

The results of the comparisons are boolean values (true or false), and they are fundamental for flow control logic.

The comparison operators in C# are:

  • == (Equality): Returns true if two values are equal.
  • != (Inequality): Returns true if two values are not equal.
  • > (Greater than): Returns true if the value on the left is greater than the value on the right.
  • < (Less than): Returns true if the value on the left is less than the value on the right.
  • >= (Greater than or equal to): Returns true if the value on the left is greater than or equal to the value on the right.
  • <= (Less than or equal to): Returns true if the value on the left is less than or equal to the value on the right.

These operators are essential for decision making in programs and are commonly used in control structures such as conditionals or loops.

List of Comparison Operators

Equality (==)

The equality operator (==) is used to check if two values are equal. It compares two values and returns true if they are equal, or false otherwise.

For example:

int a = 5;
int b = 5;
bool isEqual = (a == b); // true, since a and b are equal

Inequality (!=)

The inequality operator (!=) is used to check if two values are not equal. It compares two values and returns true if they are different, or false otherwise.

For example:

int a = 5;
int b = 3;
bool notEqual = (a != b); // true, since a is not equal to b

Greater than (>)

The greater than operator (>) is used to check if one value is greater than another.

int a = 10;
int b = 5;
bool isGreater = (a > b); // true, since a is greater than b

Less than (<)

The less than operator (<) is used to check if one value is less than another.

int a = 3;
int b = 7;
bool isLess = (a < b); // true, since a is less than b

Greater than or equal to (>=)

The greater than or equal to operator (>=) is used to check if one value is greater than or equal to another.

int a = 10;
int b = 10;
bool isGreaterOrEqual = (a >= b); // true, since a is equal to b

Less than or equal to (<=)

The less than or equal to operator (<=) is used to check if one value is less than or equal to another.

int a = 5;
int b = 7;
bool isLessOrEqual = (a <= b); // true, since a is less than b