Comparison Operators

Vaibhav • September 11, 2025

In programming, we frequently need to compare values to make decisions. Is the player's score high enough to advance to the next level? Is the user old enough to register for an account? Does the customer have enough money in their account to make a purchase? These questions all involve comparing values and acting based on the results of those comparisons.

Comparison operators allow us to compare two values and determine their relationship. Unlike arithmetic operators that produce numeric results, comparison operators produce boolean results – they evaluate to either true or false. This boolean result is fundamental to decision-making in programming, even though we haven't yet covered the control structures that use these results.

Understanding boolean results

Before diving into specific comparison operators, it's important to understand what they produce: boolean values. In C#, a boolean (bool) is a data type that can hold only two values: true or false. These values represent the logical concepts of truth and falsehood.

bool isGameOver = true;
bool hasWon = false;
bool isLoggedIn = true;

Console.WriteLine("Game over: " + isGameOver);    // Game over: True
Console.WriteLine("Player won: " + hasWon);       // Player won: False
Console.WriteLine("User logged in: " + isLoggedIn); // User logged in: True

When we use comparison operators, we're creating expressions that evaluate to these boolean values. The comparison happens, C# determines whether the relationship is true or false, and returns the appropriate boolean value.

The six comparison operators

C# provides six comparison operators that allow you to determine the relationship between two values:

  • Equal to (==) - tests if two values are equal
  • Not equal to (!=) - tests if two values are different
  • Less than (<) - tests if the left value is smaller than the right value
  • Greater than (>) - tests if the left value is larger than the right value
  • Less than or equal to (<=) - tests if the left value is smaller than or equal to the right value
  • Greater than or equal to (>=) - tests if the left value is larger than or equal to the right value

Let's see how these operators work with concrete examples:

int playerScore = 85;
int passingScore = 60;
int perfectScore = 100;

bool passedGame = playerScore >= passingScore;        // true (85 >= 60)
bool perfectGame = playerScore == perfectScore;       // false (85 == 100)
bool failedGame = playerScore < passingScore;         // false (85 < 60)
bool notPerfect = playerScore != perfectScore;        // true (85 != 100)
bool aboveMinimum = playerScore > passingScore;       // true (85 > 60)
bool atOrBelowMax = playerScore <= perfectScore;      // true (85 <= 100)

Console.WriteLine("Player passed: " + passedGame);      // Player passed: True
Console.WriteLine("Perfect score: " + perfectGame);     // Perfect score: False
Console.WriteLine("Player failed: " + failedGame);      // Player failed: False
Console.WriteLine("Not perfect: " + notPerfect);        // Not perfect: True
Console.WriteLine("Above minimum: " + aboveMinimum);    // Above minimum: True
Console.WriteLine("At or below max: " + atOrBelowMax);  // At or below max: True

Equality operators (== and !=)

The equality operators are among the most frequently used comparison operators. The equal to operator (==) tests whether two values are the same, while the not equal to operator (!=) tests whether two values are different.

It's crucial to understand the difference between the assignment operator (=) and the equality operator (==). This is one of the most common sources of confusion for beginning programmers:

  • = is assignment – it stores a value in a variable
  • == is comparison – it tests if two values are equal
int age = 25;              // Assignment: store 25 in age
bool isAdult = age == 18;  // Comparison: is age equal to 18?

Console.WriteLine("Age: " + age);           // Age: 25
Console.WriteLine("Is adult: " + isAdult);  // Is adult: False

// More examples of equality testing
int userAnswer = 42;
int correctAnswer = 42;
bool isCorrect = userAnswer == correctAnswer;
Console.WriteLine("Answer is correct: " + isCorrect);  // Answer is correct: True

// Testing inequality
int attempt1 = 7;
int attempt2 = 12;
bool differentAttempts = attempt1 != attempt2;
Console.WriteLine("Different attempts: " + differentAttempts);  // Different attempts: True

Equality operators work with all data types that can be compared, including strings (though string comparison has some nuances we'll explore later) and floating-point numbers (though floating-point equality has special considerations).

string username1 = "player123";
string username2 = "player123";
string username3 = "admin";

bool sameUser = username1 == username2;      // true
bool differentUsers = username1 != username3; // true

Console.WriteLine("Same username: " + sameUser);        // Same username: True  
Console.WriteLine("Different users: " + differentUsers); // Different users: True

double price1 = 19.99;
double price2 = 19.99;
bool samePrice = price1 == price2;           // true

Console.WriteLine("Same price: " + samePrice);          // Same price: True

Relational operators (<, >, <=, >=)

Relational operators compare the relative size or order of values. These operators are primarily used with numeric types, though they can also be used with other types that have a natural ordering (like characters based on their ASCII values).

The "less than" (<) and "greater than" (>) operators test for strict inequality, meaning the values must be different for the result to be true. The "less than or equal to" (<=) and "greater than or equal to" (>=) operators allow for equality as well.

int temperature = 75;
int freezing = 32;
int boiling = 212;

bool isFreezing = temperature <= freezing;    // false (75 <= 32)
bool isBoiling = temperature >= boiling;      // false (75 >= 212)
bool isComfortable = temperature > 65;        // true (75 > 65)
bool needsHeating = temperature < 70;         // false (75 < 70)

Console.WriteLine("Is freezing: " + isFreezing);        // Is freezing: False
Console.WriteLine("Is boiling: " + isBoiling);          // Is boiling: False  
Console.WriteLine("Is comfortable: " + isComfortable);  // Is comfortable: True
Console.WriteLine("Needs heating: " + needsHeating);    // Needs heating: False

// Testing boundary conditions
int exactValue = 100;
int testValue = 100;

bool lessThan = exactValue < testValue;        // false (100 < 100)
bool lessThanOrEqual = exactValue <= testValue; // true (100 <= 100)
bool greaterThan = exactValue > testValue;     // false (100 > 100)
bool greaterThanOrEqual = exactValue >= testValue; // true (100 >= 100)

Console.WriteLine("Less than: " + lessThan);                     // Less than: False
Console.WriteLine("Less than or equal: " + lessThanOrEqual);     // Less than or equal: True
Console.WriteLine("Greater than: " + greaterThan);               // Greater than: False
Console.WriteLine("Greater than or equal: " + greaterThanOrEqual); // Greater than or equal: True

Comparing different numeric types

C# allows you to compare values of different numeric types. When you compare an integer with a floating-point number, C# automatically converts the integer to a floating-point number for the comparison. This conversion doesn't change the stored values – it only affects how the comparison is performed.

int wholeScore = 85;
double decimalScore = 85.0;
double slightlyHigher = 85.1;

bool exactMatch = wholeScore == decimalScore;      // true (85 == 85.0)
bool almostEqual = wholeScore == slightlyHigher;   // false (85 == 85.1)
bool wholeIsLess = wholeScore < slightlyHigher;    // true (85 < 85.1)

Console.WriteLine("Exact match: " + exactMatch);     // Exact match: True
Console.WriteLine("Almost equal: " + almostEqual);   // Almost equal: False
Console.WriteLine("Whole is less: " + wholeIsLess);  // Whole is less: True

// Comparing integers with decimal literals
int quantity = 5;
bool hasEnough = quantity >= 3.5;                 // true (5 >= 3.5)
bool tooMany = quantity > 10.0;                   // false (5 > 10.0)

Console.WriteLine("Has enough: " + hasEnough);       // Has enough: True
Console.WriteLine("Too many: " + tooMany);           // Too many: False

Character comparisons

Characters in C# can be compared using the same relational operators used for numbers. Characters are compared based on their ASCII values, which means they follow alphabetical order for letters and numerical order for digits.

char letter1 = 'A';
char letter2 = 'B';
char letter3 = 'a';
char digit1 = '5';
char digit2 = '7';

bool letterOrder = letter1 < letter2;        // true ('A' < 'B')
bool caseComparison = letter1 < letter3;     // true ('A' < 'a' because uppercase comes before lowercase in ASCII)
bool digitOrder = digit1 < digit2;           // true ('5' < '7')

Console.WriteLine("A < B: " + letterOrder);           // A < B: True
Console.WriteLine("A < a: " + caseComparison);        // A < a: True
Console.WriteLine("5 < 7: " + digitOrder);            // 5 < 7: True

// Character equality
char userInput = 'Y';
char confirmationChar = 'Y';
bool confirmed = userInput == confirmationChar;

Console.WriteLine("Confirmed: " + confirmed);         // Confirmed: True

String comparisons

Strings can be compared for equality using == and != operators. String comparison in C# is case-sensitive, meaning uppercase and lowercase letters are considered different.

string password = "SecretPassword";
string userInput1 = "SecretPassword";
string userInput2 = "secretpassword";
string userInput3 = "WrongPassword";

bool correctPassword1 = password == userInput1;    // true (exact match)
bool correctPassword2 = password == userInput2;    // false (different case)
bool correctPassword3 = password == userInput3;    // false (different content)

Console.WriteLine("Correct password (exact): " + correctPassword1);      // Correct password (exact): True
Console.WriteLine("Correct password (case): " + correctPassword2);       // Correct password (case): False
Console.WriteLine("Correct password (wrong): " + correctPassword3);      // Correct password (wrong): False

// String inequality
string expectedResponse = "yes";
string actualResponse = "no";
bool responsesMatch = expectedResponse == actualResponse;      // false
bool responsesDiffer = expectedResponse != actualResponse;     // true

Console.WriteLine("Responses match: " + responsesMatch);       // Responses match: False
Console.WriteLine("Responses differ: " + responsesDiffer);     // Responses differ: True

Operator precedence with comparisons

Comparison operators have lower precedence than arithmetic operators, which means arithmetic operations are performed before comparisons. This allows you to write expressions that compute values and then compare them.

int a = 10;
int b = 5;
int c = 3;

// Arithmetic is performed first, then comparison
bool result1 = a + b > c * 5;          // (10 + 5) > (3 * 5) = 15 > 15 = false
bool result2 = a - b == c + 2;         // (10 - 5) == (3 + 2) = 5 == 5 = true
bool result3 = a * 2 != b + c;         // (10 * 2) != (5 + 3) = 20 != 8 = true

Console.WriteLine("15 > 15: " + result1);     // 15 > 15: False
Console.WriteLine("5 == 5: " + result2);      // 5 == 5: True
Console.WriteLine("20 != 8: " + result3);     // 20 != 8: True

// You can use parentheses for clarity even when not needed
bool result4 = (a + b) > (c * 5);      // Same as result1, but clearer
Console.WriteLine("With parentheses: " + result4);  // With parentheses: False

Chaining comparisons (common mistake)

Unlike mathematics, you cannot chain comparison operators in C# the way you might expect. In mathematics, you might write "10 < x < 20" to mean that x is between 10 and 20, but this doesn't work as expected in C#.

int value = 15;

// This doesn't work as expected in C#!
// bool inRange = 10 < value < 20;    // This won't compile correctly

// Instead, you need to break it into separate comparisons
bool greaterThan10 = value > 10;       // true
bool lessThan20 = value < 20;          // true

Console.WriteLine("Value > 10: " + greaterThan10);   // Value > 10: True
Console.WriteLine("Value < 20: " + lessThan20);      // Value < 20: True

// To check if a value is in a range, you would need to use logical operators
// (which we'll cover in the next lesson), but for now, separate comparisons work
bool condition1 = value > 10;
bool condition2 = value < 20;
Console.WriteLine("Both conditions: " + condition1 + " and " + condition2);

Chaining comparison operators like 10 < x < 20 doesn't work in C# the way it does in mathematics. Each comparison must be written separately and combined using logical operators (covered in the next lesson).

Floating-point comparison considerations

When comparing floating-point numbers (float, double), be aware that floating-point arithmetic can introduce tiny rounding errors. This means that calculations that should theoretically produce the same result might be slightly different when compared for exact equality.

double result1 = 0.1 + 0.2;           // Might not exactly equal 0.3
double result2 = 0.3;

Console.WriteLine("Result1: " + result1);     // Result1: 0.30000000000000004
Console.WriteLine("Result2: " + result2);     // Result2: 0.3

bool exactEqual = result1 == result2;         // Might be false due to rounding
Console.WriteLine("Exactly equal: " + exactEqual);  // Exactly equal: False

// For now, just be aware of this issue
// Better approaches for floating-point comparison exist but require more advanced concepts
double difference = result1 - result2;
Console.WriteLine("Difference: " + difference);     // Shows the tiny difference

For now, just be aware that floating-point comparisons can sometimes produce unexpected results due to rounding errors. Exact equality comparisons with floating-point numbers should be used carefully.

Practical applications of comparison operators

Even though we haven't covered control structures yet, comparison operators are useful for creating boolean values that represent the state of your program or the results of evaluations.

// User account validation
string enteredUsername = "john_doe";
string validUsername = "john_doe";
string enteredPassword = "secret123";
string validPassword = "secret123";

bool usernameValid = enteredUsername == validUsername;
bool passwordValid = enteredPassword == validPassword;

Console.WriteLine("Username valid: " + usernameValid);     // Username valid: True
Console.WriteLine("Password valid: " + passwordValid);     // Password valid: True

// Game scoring system
int currentScore = 1250;
int highScore = 1000;
int maxPossibleScore = 2000;

bool newHighScore = currentScore > highScore;
bool perfectScore = currentScore == maxPossibleScore;
bool scoringComplete = currentScore >= 0;  // Simple validity check

Console.WriteLine("New high score: " + newHighScore);       // New high score: True
Console.WriteLine("Perfect score: " + perfectScore);        // Perfect score: False
Console.WriteLine("Scoring complete: " + scoringComplete);  // Scoring complete: True

// Age verification
int userAge = 17;
int minimumAge = 18;
int seniorAge = 65;

bool isMinor = userAge < minimumAge;
bool isAdult = userAge >= minimumAge;
bool isSenior = userAge >= seniorAge;

Console.WriteLine("Is minor: " + isMinor);         // Is minor: True
Console.WriteLine("Is adult: " + isAdult);         // Is adult: False
Console.WriteLine("Is senior: " + isSenior);       // Is senior: False

Comparison operators are often used to create meaningful boolean variables that make your code more readable. Instead of repeating complex comparisons, store the result in a well-named boolean variable.

Common mistakes and best practices

When working with comparison operators, there are several common pitfalls to avoid:

Confusing assignment (=) with equality (==): This is the most common mistake beginners make. Remember that = stores a value, while == compares values.

Assuming mathematical chaining works: You cannot write 10 < x < 20 in C#. Each comparison must be separate.

Case sensitivity in string comparisons: Remember that "Hello" and "hello" are not equal in C#.

Floating-point equality issues: Be cautious when comparing floating-point numbers for exact equality due to potential rounding errors.

Summary

Comparison operators are fundamental tools for determining relationships between values in C#. They evaluate expressions and return boolean results that represent whether the comparison is true or false.

Key points to remember:

  • Comparison operators return boolean values (true or false)
  • == tests for equality, != tests for inequality
  • <, >, <=, >= test for relative size relationships
  • Don't confuse = (assignment) with == (comparison)
  • Arithmetic operations are performed before comparisons
  • You cannot chain comparisons like in mathematics
  • String comparisons are case-sensitive
  • Be careful with floating-point equality comparisons

Comparison operators form the foundation for decision-making in programming. While we haven't yet covered the control structures that use these boolean results, understanding how to compare values is essential preparation for the conditional logic and loops that make programs truly interactive and intelligent. In our next lesson, we'll explore logical operators, which allow you to combine multiple boolean values to create more complex conditional expressions.