How to Use Comparison Operators in C# - Simple Guide
In C#, you use
comparison operators like ==, !=, <, >, <=, and >= to compare values. These operators return true or false depending on whether the comparison is correct.Syntax
Comparison operators in C# compare two values and return a boolean result (true or false).
Here are the common operators:
==: Equal to!=: Not equal to<: Less than>: Greater than<=: Less than or equal to>=: Greater than or equal to
csharp
bool result = (5 == 5); // true bool notEqual = (5 != 3); // true bool lessThan = (3 < 5); // true bool greaterThan = (7 > 2); // true bool lessOrEqual = (4 <= 4); // true bool greaterOrEqual = (6 >= 7); // false
Example
This example shows how to use comparison operators to compare two numbers and print the results.
csharp
using System; class Program { static void Main() { int a = 10; int b = 20; Console.WriteLine($"a == b: {a == b}"); Console.WriteLine($"a != b: {a != b}"); Console.WriteLine($"a < b: {a < b}"); Console.WriteLine($"a > b: {a > b}"); Console.WriteLine($"a <= b: {a <= b}"); Console.WriteLine($"a >= b: {a >= b}"); } }
Output
a == b: False
a != b: True
a < b: True
a > b: False
a <= b: True
a >= b: False
Common Pitfalls
One common mistake is using = (assignment) instead of == (comparison). This causes errors or unexpected behavior.
Also, comparing floating-point numbers directly can be unreliable due to precision issues.
csharp
int x = 5; // Wrong: assigns 10 to x instead of comparing // if (x = 10) { Console.WriteLine("x is 10"); } // Error // Correct: if (x == 10) { Console.WriteLine("x is 10"); } else { Console.WriteLine("x is not 10"); }
Output
x is not 10
Quick Reference
| Operator | Meaning | Example | Result |
|---|---|---|---|
| == | Equal to | 5 == 5 | true |
| != | Not equal to | 5 != 3 | true |
| < | Less than | 3 < 5 | true |
| > | Greater than | 7 > 2 | true |
| <= | Less than or equal to | 4 <= 4 | true |
| >= | Greater than or equal to | 6 >= 7 | false |
Key Takeaways
Use == to check if two values are equal and != to check if they are not equal.
Comparison operators return true or false based on the relationship between values.
Avoid using = (assignment) when you mean to compare with ==.
Be cautious comparing floating-point numbers directly due to precision limits.
Use comparison operators in conditions like if statements to control program flow.