C# Operators
Operators do work on values: they calculate, compare and combine them.
Arithmetic Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Add | 12 + 5 | 17 |
- | Subtract | 12 - 5 | 7 |
* | Multiply | 12 * 5 | 60 |
/ | Divide | 12 / 5 | 2 |
% | Remainder | 12 % 5 | 2 |
++ | Add 1 | x++ | |
-- | Subtract 1 | x-- |
Example
csharp
int totalDays = 45;
int weeks = totalDays / 7;
int days = totalDays % 7;
Console.WriteLine($"{weeks} weeks and {days} days");
Console.WriteLine(45 / 7.0);Output
6 weeks and 3 days 6.428571428571429
Dividing two int values gives an int and drops the decimal part. Use at least one double (like 7.0) to get the decimal answer.
Assignment Operators
| Operator | Same as |
|---|---|
x += 5 | x = x + 5 |
x -= 5 | x = x - 5 |
x *= 5 | x = x * 5 |
x /= 5 | x = x / 5 |
x %= 5 | x = x % 5 |
Example
csharp
int points = 100;
points += 50; // bonus
points -= 30; // penalty
points *= 2; // double weekend
Console.WriteLine(points);Output
240
Comparison Operators
These give a bool: True or False.
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
> / < | Greater / less than |
>= / <= | Greater or equal / less or equal |
Logical Operators
&&and: both sides must be true||or: at least one side must be true!not: reverses the value
Example
csharp
int age = 17;
bool withParent = true;
Console.WriteLine(age >= 18);
Console.WriteLine(age >= 18 || withParent);
Console.WriteLine(!withParent);Output
False True False
The Math Class
C# has a built-in Math class for common calculations:
| Method | Example | Result |
|---|---|---|
Math.Max(a, b) | Math.Max(4, 9) | 9 |
Math.Min(a, b) | Math.Min(4, 9) | 4 |
Math.Sqrt(x) | Math.Sqrt(64) | 8 |
Math.Pow(x, y) | Math.Pow(2, 5) | 32 |
Math.Round(x) | Math.Round(4.6) | 5 |
Math.Abs(x) | Math.Abs(-7) | 7 |
Example
csharp
double bill = 2347.567;
Console.WriteLine(Math.Round(bill, 2));
Console.WriteLine(Math.Sqrt(144));Output
2347.57 12
Order of Operations
*, / and % happen before + and -. Use brackets to be clear:
Example
csharp
int a = 6 + 4 * 2; // 14
int b = (6 + 4) * 2; // 20Exercise
Exercise
What does Console.WriteLine(20 % 6); print?
