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:
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:
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:
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:
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:
Sure it's short and concise, but with the addition assignment operator, we can make it even shorter:
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!
Last updated
Was this helpful?