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
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); // FalseUsing 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.