Search code examples
c#post-incrementunary-operator

Shortcut syntax for doing var = var + n?


I'd like to increment my var value of n, using a similar structure of the post-increment solution like var++.

The post-increment is like this:

int var = 0;
var++; // var = var + 1

I'd like to increment var of n, with n = 4 for example. What's the correct syntax ?

int var = 0;
var++4; // var = var + 4 but obviously not working;

Solution

  • what you are looking for is actually a Compound assignment with arithmetic operators

    int a = 5;
    a += 9;
    Console.WriteLine(a);  // output: 14
    
    a -= 4;
    Console.WriteLine(a);  // output: 10
    
    a *= 2;
    Console.WriteLine(a);  // output: 20
    
    a /= 4;
    Console.WriteLine(a);  // output: 5
    
    a %= 3;
    Console.WriteLine(a);  // output: 2