Comparison Operators in C#

Comparison operators are used to compare two operands and return a Boolean result (true or false). They can be used to control the flow of a program by determining if the execution of a conditional statement or loop should stop or continue based on the result of the comparison.

Comparison operators are also known as relational operators, as they define the relation between two operands when used.

If you aren’t generally familiar with operators and precedence in programming, then I suggest that you check out my blog post on Working with Operators in C#.

Here are the comparison operators used in C#:

Operand Description
> Greater than operator. If the operand on the left is greater than the operand on the right, then the condition is true.
< Less than operator. If the operand on the left is less than the operand on the right, then the condition is true.
>= Greater than or equal to operator. If the operand on the left is greater than or equal to the operand on the right, then the condition is true.<
<= Less than or equal to operator. If the operand on the left is less than or equal to the operand on the right, then the condition is true.
== Equality operator. If both operands are equal, then the condition is true.
!= Difference operator. If both operands are not equal, then the condition is true.

Example using comparison operators

int x = 3;
int y = 12;

Console.WriteLine(x > y);   //  Output: False
Console.WriteLine(x < y);   //  Output: True
Console.WriteLine(x >= y);  //  Output: False
Console.WriteLine(x <= y);  //  Output: True
Console.WriteLine(x == y);  //  Output: False
Console.WriteLine(x != y);  //  Output: True
comments powered by Disqus