Assignment operators
Learn shortcut assignments with =, +=, -=, *=, /= and ++/--.
Comparison operators
To compare two values you use comparison operators: == equal, != not equal, < less than, > greater than, <= less than or equal, >= greater than or equal. The result is always a bool (true or false).
For example, age >= 18 returns true when the age is greater than or equal to 18. You can use this result in an if condition.
Type safety and ==
C# is a type-safe language, so == raises a compile error on mismatched types. 5 == "5" is invalid because the left side is int and the right side is string.
Numeric types do mix: 5 == 5.0 works because C# promotes the int to double and returns true. Matching the types before comparison is your responsibility.
Exercise Compare two scores
Write an if with the condition score1 > score2. When true, print "high" with Console.WriteLine; otherwise print "low". You must use an else branch.
Show example solution
For the comparison, write if (score1 > score2) { ... } else { ... }.
Example solution:
using System;
class Program
{
static void Main()
{
int score1 = 85;
int score2 = 70;
// Compare and print
if (score1 > score2)
{
Console.WriteLine("high");
}
else
{
Console.WriteLine("low");
}
}
}
Test yourself
-
What is the output of Console.WriteLine(7 > 3);?
Console.WriteLine(7 > 3);- 7
- true
- True
- 3
Show answer
True — Correct. 7 > 3 is true; C# prints it with a capital T.
-
Write the pass condition
int average = 70; bool pass = average ____ 50; Console.WriteLine(pass);Show answer
int average = 70; bool pass = average >= 50; Console.WriteLine(pass); -
Match each operator to its meaning
- ==
- Equal
- !=
- Not equal
- <
- Less than
- >
- Greater than