C# Comparison Operators

Comparison operators are used to compare two values. Every comparison produces a bool, meaning the answer is always either true or false. These operators are the foundation of decision making in your programs, and you will use them constantly inside if statements and loops.

Comparing two values

A comparison asks a yes or no question about two values, such as "is a greater than b?" C# answers with true or false. Notice that checking for equality uses two equals signs, ==, so it is not confused with assignment, which uses one.

Comparison operators

OperatorMeaningExampleResult
==Equal to5 == 5true
!=Not equal to5 != 3true
>Greater than5 > 3true
<Less than5 < 3false
>=Greater than or equal to5 >= 5true
<=Less than or equal to3 <= 2false

Storing comparison results

int a = 5;
int b = 3;
bool isBigger = a > b;   // true
bool isEqual = a == b;   // false
Console.WriteLine(isBigger); // True
Console.WriteLine(isEqual);  // False
Note: A very common beginner mistake is writing = when you mean ==. Remember: one equals sign assigns a value, two equals signs compare for equality. The compiler will usually warn you if you mix them up inside a condition.

Using comparisons in decisions

Comparison operators really shine inside if statements, where the true or false result decides which block of code runs. Here the program checks whether a test score is high enough to pass.

A comparison inside an if

int score = 72;
if (score >= 50)
{
    Console.WriteLine("You passed!");
}
else
{
    Console.WriteLine("Try again.");
}
  • Every comparison evaluates to a bool: either true or false.
  • Use == to check equality and != to check inequality.
  • Comparison results are often stored in a bool variable or used directly in an if condition.