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:
Syntax
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
- Writing
if (a = b)instead ofif (a == b);=assigns a value, and forintvalues the assignment is not abool, so the code does not compile. - Comparing floating-point results with
==, such as0.1 + 0.2 == 0.3, which isfalsebecause of tiny rounding errors; compare within a small tolerance instead. - 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 (stringis the exception and compares by value).
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: