Labs ICT
โญ Pro Login

Operators

Operators are symbols that tell C# to perform some operation on values. You have probably used them without even knowing their names. Let me break them down for you.

Arithmetic Operators

These are the ones you learned in primary school. They work exactly how you would expect:

int a = 10;
int b = 3;

Console.WriteLine(a + b);   // 13 (addition)
Console.WriteLine(a - b);   // 7  (subtraction)
Console.WriteLine(a * b);   // 30 (multiplication)
Console.WriteLine(a / b);   // 3  (division โ€” notice it drops the decimal)
Console.WriteLine(a % b);   // 1  (modulus โ€” the remainder)

See that division result? 10 / 3 gives you 3, not 3.333. That is because when you divide two integers, C# gives you an integer result. If you want the decimal, you need at least one of the numbers to be a double or float:

Console.WriteLine(10.0 / 3);  // 3.3333...

Comparison Operators

These operators compare two values and return a boolean โ€” either true or false:

int x = 5;
int y = 10;

Console.WriteLine(x == y);  // false (equal to)
Console.WriteLine(x != y);  // true  (not equal to)
Console.WriteLine(x > y);   // false (greater than)
Console.WriteLine(x < y);   // true  (less than)
Console.WriteLine(x >= 5);  // true  (greater than or equal to)
Console.WriteLine(x <= 3);  // false (less than or equal to)

These will come in handy when we start writing conditionals in the next section. You will use them all the time.

Logical Operators

These combine multiple conditions together:

int age = 25;
bool hasID = true;

// AND โ€” both conditions must be true
Console.WriteLine(age >= 18 && hasID);   // true

// OR โ€” at least one condition must be true
Console.WriteLine(age < 18 || hasID);    // true

// NOT โ€” flips true to false and vice versa
Console.WriteLine(!hasID);               // false

Think of && as "both must be true", || as "at least one must be true", and ! as "flip it". Simple as that.

Assignment Operators

You already know = for assigning values. But there are shortcuts that save you time:

int count = 10;

count += 5;    // same as count = count + 5  โ†’ 15
count -= 3;    // same as count = count - 3  โ†’ 12
count *= 2;    // same as count = count * 2  โ†’ 24
count /= 4;    // same as count = count / 4  โ†’ 6
count %= 4;    // same as count = count % 4  โ†’ 2

These are called compound assignment operators. They make your code shorter and easier to read once you get used to them.

๐Ÿงช Quick Quiz

What is the result of 10 / 3 in C# with integer variables?