Skip to content

C# - Relational Operators

What Are Relational and Equality Operators?

Section titled “What Are Relational and Equality Operators?”

Relational and equality operators are used to compare two operands and determine their relationship. The result of a comparison is always a Boolean value: true or false. These operators are fundamental to controlling program flow with if statements, while loops, and other control structures.

The following table shows all the relational and equality operators supported by C#. Assume int score = 95; and int passingScore = 70;.

OperatorNameDescriptionExample
==Equal toChecks if the values of two operands are equal.(score == 95) is true.
!=Not equal toChecks if the values of two operands are not equal.(score != passingScore) is true.
>Greater thanChecks if the value of the left operand is greater than the right.(score > passingScore) is true.
<Less thanChecks if the value of the left operand is less than the right.(score < passingScore) is false.
>=Greater than or equal toChecks if the left operand is greater than or equal to the right.(score >= 95) is true.
<=Less than or equal toChecks if the left operand is less than or equal to the right.(score <= passingScore) is false.

The primary use of these operators is within if-else blocks to make decisions.

using System;
int temperature = 25;
if (temperature > 30)
{
Console.WriteLine("It's a hot day!");
}
else if (temperature < 10)
{
Console.WriteLine("It's a cold day!");
}
else
{
Console.WriteLine("The weather is pleasant.");
}
// Output: The weather is pleasant.

Relational operators are essential for controlling the termination condition of loops.

using System;
// This loop will execute as long as 'i' is less than or equal to 5.
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"Iteration: {i}");
}
// Output:
// Iteration: 1
// Iteration: 2
// Iteration: 3
// Iteration: 4
// Iteration: 5

It’s critical to understand how the == operator behaves with different kinds of types:

  • For value types (like int, double, bool, struct), == compares their actual values.
  • For most reference types (like a custom class), == compares their memory addresses (references). It checks if two variables point to the exact same object, not if their contents are the same.
public record Person(string Name, int Age);
// Value Type Comparison (structs or records)
var p1 = new Person("Alice", 30);
var p2 = new Person("Alice", 30);
Console.WriteLine(p1 == p2); // Output: true (for records), false (for classes)
// Reference Type Comparison (classes)
var list1 = new List<int> { 1, 2 };
var list2 = new List<int> { 1, 2 };
var list3 = list1;
Console.WriteLine(list1 == list2); // Output: false (different objects in memory)
Console.WriteLine(list1 == list3); // Output: true (point to the same object)

Note: The string type is a special reference type where == is overloaded to compare content, behaving like a value type for equality checks.

  • Use == for comparison, not =: A single equals sign (=) is the assignment operator. if (x = 5) is a common bug; it assigns 5 to x and will likely not behave as you expect in a conditional.
  • Use Equals() for object content comparison: To check if two different objects have the same values (value equality), override the Equals() method in your class or use a record type, which does this for you automatically.
  • Be explicit with string comparisons: For case-insensitive string comparisons, don’t convert both strings to lower/upper case. Use the more efficient and clear string.Equals(other, StringComparison.OrdinalIgnoreCase).
  • Avoid redundant boolean comparisons: Instead of if (isValid == true), simply write if (isValid). Instead of if (isComplete == false), write if (!isComplete).

Real-World Use Case: Validating User Input

Section titled “Real-World Use Case: Validating User Input”

Relational operators are constantly used for validation.

using System;
Console.WriteLine("Please enter your age:");
string input = Console.ReadLine() ?? "";
if (int.TryParse(input, out int age))
{
if (age >= 18)
{
Console.WriteLine("You are eligible to vote.");
}
else
{
Console.WriteLine("You are not yet eligible to vote.");
}
}
else
{
Console.WriteLine("That is not a valid age.");
}