Operators are special symbols used to perform operations on variables and values. Whether you are doing math, comparing numbers, or combining logic, operators are the engine behind it all.
C# divides operators into several groups:
Arithmetic operators perform common mathematical operations.
| Operator | Name | Description | Example |
|---|---|---|---|
+ |
Addition | Adds together two values | x + y |
- |
Subtraction | Subtracts one value from another | x - y |
* |
Multiplication | Multiplies two values | x * y |
/ |
Division | Divides one value by another | x / y |
% |
Modulus | Returns the remainder of division | x % y |
++ |
Increment | Increases the value of a variable by 1 | x++ |
-- |
Decrement | Decreases the value of a variable by 1 | x-- |
Assignment operators are used to assign values to variables. The most common is the equal sign (=). You can also combine assignment with math operators to write shorter code.
int x = 10; x += 5; // This is the exact same as writing: x = x + 5;
Comparison operators are used to compare two values. They always return a boolean value (true or false), which is extremely important for making decisions in your code (like if statements).
| Operator | Name | Example |
|---|---|---|
== |
Equal to | x == y |
!= |
Not equal | x != y |
> |
Greater than | x > y |
< |
Less than | x < y |
>= |
Greater than or equal to | x >= y |
<= |
Less than or equal to | x <= y |
Logical operators are used to determine the logic between variables or values. They also evaluate to boolean results.
&& (Logical AND): Returns true if BOTH statements are true. (e.g., x < 5 && x < 10)|| (Logical OR): Returns true if AT LEAST ONE of the statements is true. (e.g., x < 5 || x < 4)! (Logical NOT): Reverses the result. Returns false if the result is true. (e.g., !(x < 5 && x < 10))using System;class Program { static void Main() { int x = 5; Console.WriteLine(x > 3 && x < 10); // True, because 5 is greater than 3 AND less than 10 } }
Which operator is used to compare if two values are equal?