← Back to C# Course | Chapter 3: Operators | Lesson 2 of 6

Comparison Operators

Comparison operators ask questions like 'is this bigger?' or 'are these equal?' and answer with true or false. They are like a scale weighing two things.

In this page:

  1. Comparison Operators
Syntax
csharp
bool result = a == b;
bool result = a != b;
bool result = a > b;
bool result = a <= b;

Comparison Operators

Comparison operators (==, !=, >, <, >=, <=) compare two values and always produce a bool. For value types like int, == compares actual values. For reference types, == compares references unless the type overrides it.

Note: Use .Equals() or override == when you need value-based equality on custom classes.

Example: Comparison Operators

markup
using System;

class Program
{
    static void Main(string[] args)
    {
        int a = 5, b = 8;

        Console.WriteLine(a == b);
        Console.WriteLine(a != b);
        Console.WriteLine(a < b);
        Console.WriteLine(a >= 5);
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Writing if (a = b) instead of if (a == b); = assigns a value, and for int values the assignment is not a bool, so the code does not compile.
  2. Comparing floating-point results with ==, such as 0.1 + 0.2 == 0.3, which is false because of tiny rounding errors; compare within a small tolerance instead.
  3. Expecting == to compare contents for every reference type, when for classes without an overloaded == it only checks whether both variables point to the same object (string is the exception and compares by value).
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.