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.
x + y
x == y
x && yArithmetic 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.
using System;
class Program {
static void Main() {
int x = 10, y = 3;
Console.WriteLine(x + y);
Console.WriteLine(x % y);
}
}13
1+ adds the numbers, and % returns the remainder of dividing 10 by 3.
using System;
class Program {
static void Main() {
int age = 20;
bool canVote = age >= 18;
Console.WriteLine(canVote);
}
}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.
