C# ยท Chapter 11 of 46

C# Operators

Operators are symbols used to perform operations on variables and values. C# has arithmetic operators (+, -, *, /, %), assignment operators (=, +=, -=), comparison operators (==, !=, >, <), and logical operators (&&, ||, !).

Understanding operator precedence โ€” the order in which operations are evaluated โ€” is important for writing correct expressions, just like in mathematics.

Syntax
x + y
x == y
x && y

Arithmetic and assignment operators

Arithmetic operators perform math: + adds, - subtracts, * multiplies, / divides, and % gives the remainder. Assignment operators like += combine an operation with assignment, e.g. `x += 5` means `x = x + 5`.

Comparison and logical operators

Comparison operators like == and > compare two values and return a bool. Logical operators && (and), || (or), and ! (not) combine or invert boolean expressions.

Example 1 (csharp)
using System;

class Program {
  static void Main() {
    int x = 10, y = 3;
    Console.WriteLine(x + y);
    Console.WriteLine(x % y);
  }
}
Output
13
1

+ adds the numbers, and % returns the remainder of dividing 10 by 3.

Example 2 (csharp)
using System;

class Program {
  static void Main() {
    int age = 20;
    bool canVote = age >= 18;
    Console.WriteLine(canVote);
  }
}
Output
True

>= compares age with 18 and returns a boolean value.

Key points

  • Arithmetic operators include +, -, *, /, and %.
  • Assignment operators like += combine an operation with assignment.
  • Comparison operators return a bool result.
  • Logical operators && , || and ! combine boolean expressions.
๐Ÿ’ก Note: Integer division truncates the decimal part, so 7 / 2 gives 3, not 3.5, unless at least one operand is a double.

๐Ÿ“ Quick Quiz

1. What does the % operator return?

2. What does x += 5 mean?

3. Which operator means logical AND?