C# Comparison Operators
Comparison operators in C# are used to compare two values or variables. These operators return a boolean value (true
or false
) depending on the result of the comparison. They are commonly used in conditional statements to control the flow of the program.
Key Topics
Equal to (==)
The ==
operator checks if two values are equal. It returns true
if the values are the same and false
otherwise.
Example: Equal to
int a = 10;
int b = 10;
Console.WriteLine(a == b); // True
Output:
Not equal to (!=)
The !=
operator checks if two values are not equal. It returns true
if the values are different and false
if they are the same.
Example: Not equal to
int a = 10;
int b = 20;
Console.WriteLine(a != b); // True
Output:
Greater than (>)
The >
operator checks if the left-hand value is greater than the right-hand value.
Example: Greater than
int x = 15;
int y = 10;
Console.WriteLine(x > y); // True
Output:
Less than (<)
The <
operator checks if the left-hand value is less than the right-hand value.
Example: Less than
int a = 5;
int b = 8;
Console.WriteLine(a < b); // True
Output:
Greater than or equal to (>=)
The >=
operator checks if the left-hand value is greater than or equal to the right-hand value.
Example: Greater than or equal to
int a = 10;
int b = 10;
Console.WriteLine(a >= b); // True
Output:
Less than or equal to (<=)
The <=
operator checks if the left-hand value is less than or equal to the right-hand value.
Example: Less than or equal to
int x = 7;
int y = 10;
Console.WriteLine(x <= y); // True
Output:
Key Takeaways
==
: Returns true if the two values are equal.!=
: Returns true if the two values are not equal.>
: Returns true if the left-hand value is greater than the right-hand value.<
: Returns true if the left-hand value is less than the right-hand value.>=
: Returns true if the left-hand value is greater than or equal to the right-hand value.<=
: Returns true if the left-hand value is less than or equal to the right-hand value.