TOC

The community is working on translating this tutorial into Serbian, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Operators:

Addition assignment operators

We have previously looked into the increment/decrement operator which simply adds or subtracts 1 to/from a value, but in most cases, you probably want more flexibility in how much you're looking to add or subtract. For this, we can use the addition assignment operator. Without it, adding to a value looks like this:

int userAge = 38; 
userAge = userAge + 4;

Not really very long or complicated, but since we're always looking into ways we can make our code even shorter, we can use the addition assignment operator instead:

int userAge = 38; 
userAge += 4;

Notice the difference: Instead of re-stating the name of the value, to indicate that we're looking to add something to it and assign it back to the very same variable, we say it all with the operator += (plus-equals). You can of course do the same when you want to subtract a value:

int userAge = 42;   
userAge -= 4;

This probably seems obvious, but what might be less obvious is that you can do it with multiplication and division and it's just as easy:

int userAge = 42;   

userAge *= 2;  
Console.WriteLine("User age: " + userAge);  

userAge /= 2;  
Console.WriteLine("User age: " + userAge);  

Console.ReadKey();

Adding to strings

So far, we have worked exclusively with numbers, but the addition assignment operator can be used for e.g. strings as well, in exactly the same way. Let me illustrate it with a similar set of examples – first without the addition assignment operator:

string userName = "John";   
userName = userName + " Doe";

Sure it's short and concise, but with the addition assigment operator, we can make it even shorter:

string userName = "John"; 
userName += " Doe";  

Nice and easy!

Summary

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!