C sharp - Increment and Decrement Operators in C#
The increment (++) and decrement (--) operators are unary operators in C# that increase or decrease a numeric variable’s value by 1.
Definition
| Operator | Meaning | Effect |
|---|---|---|
++ |
Increment operator | Adds 1 to a value |
-- |
Decrement operator | Subtracts 1 from a value |
These operators can be used in two forms:
-
Prefix:
++xor--x -
Postfix:
x++orx--
Prefix vs Postfix
| Type | Syntax | Operation Order |
|---|---|---|
| Prefix | ++x |
Increments first, then uses the value |
| Postfix | x++ |
Uses the value first, then increments |
Use with Loops
These operators are often used in loops:
for (int i = 0; i < 5; i++) // i++ increments i by 1 after each iteration
{
Console.WriteLine(i);
}
| Operator | Effect | Example (initial x = 5) |
Result |
|---|---|---|---|
++x |
Increment, then use | int y = ++x; |
x = 6, y = 6 |
x++ |
Use, then increment | int y = x++; |
x = 6, y = 5 |
--x |
Decrement, then use | int y = --x; |
x = 4, y = 4 |
x-- |
Use, then decrement | int y = x--; |
x = 4, y = 5 |