TOC

This article is currently in the process of being translated into Ukrainian (~15% done).

Operators:

Increment/decrement operators

Іноді при роботі зі значеннями, особливо числовими, ви можете помітити постійну потребу в додаванні чи відніманні 1. Звичайно, це дуже легко зробити - спочатку берете одне значення, далі додаєте 1 і, нарешті, призначаєте отримане значення початковій змінній. Наприклад, ось так:

int userAge = 41; 
userAge = userAge + 1;

The userAge variable now contains the value of 42 instead of 41 – easy! You can of course do the same thing when you want to subtract by 1:

userAge = userAge - 1; 

Postfix increment/decrement

However, C# has a much shorter operator for taking care of this job: The increment/decrement operator. It simply consists of two plus or two minus signs right after each other. Here's the first example, rewritten to use this operator:

int userAge = 41; 
userAge++;
Console.WriteLine("Age of user: " + userAge);

Як бачите, результат такий самий, але зверніть увагу на скільки він коротший! Та ми можемо зробити його ще коротшим, оскільки цей оператор, звичайно, може бути використаний у вже існуючому виразі:

int userAge = 41; 
Console.WriteLine("Age of user: " + userAge++);

But wait a minute – when testing this, you will see that the userAge is still printed as 41. Why? Because we're using the postfix version, which is evaluated AFTER the surrounding statement. In other words, the line is printed before the value is incremented. This will be the behavior you want in some cases, but it's not optimal for this specific usecase. What you need is the prefix increment operator.

Prefix increment/decrement

This operator looks exactly like the postfix version, but instead of appearing after the variable, it will appear before, instructing the interpreter to evaluate it before evaluating the surrounding statement:

int userAge = 41; 
Console.WriteLine("Age of user: " + ++userAge);

This will have the desired effect, where the userAge is incremented before the line is printed. Now, it may look a bit confusing with three + signs, but the first is for the string concatenation, while the last two are the actual operator. If you prefer it, you can wrap the increment statement with parentheses to make it clear what belongs together:

Console.WriteLine("Age of user: " + (++userAge)); 

That's all up to you to decide – it works exactly the same!

And of course, you can use the decrement operator in exactly the same way as illustrated above. Here's the postfix version:

int userAge = 41; 
Console.WriteLine("Age of user: " + (userAge--));

And the prefix version:

int userAge = 41; 
Console.WriteLine("Age of user: " + (--userAge));

Summary

So, these were the increment and decrement operators. They are great for a very specific use case: When you want to increment or decrement a value by 1. In the next chapter, we will look into the addition assignment operator, which looks a lot like this one, but has a slightly broader use.

As with several other C# operators, this one falls under the term "syntactical sugar" - the same task can be accomplished without this specific operator, but with it, your code becomes shorter. Whether it becomes more readable is very subjective – some people like them, while others feel that their code becomes easier to read and understand without them. It's really all to you!


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!