Are there any side-effects in using `x += 1` rather than `++x` in C#?

153 views Asked by At

I've always written for loops in C# using for (int i = 0; i < 10; i++).

I've been reading up on the best-practices for JavaScript (JavaScript: The Good Parts), and one of them is to prefer x += 1 over x++.

Are there any differences, in C#, between the two in areas such as performance, atomicity, and functionality.

I ask, because there are functional differences between ++x and x++ in C# (and C++ and probably most other C based languages); the former being pre-increment where it increments the variable and then returns the value, and the latter being post-increment where it returns the value and then increments it (actually, these two subtle differences are what's piqued my interest in adopting the x += 1 strategy in my C# code)

Update:

Here's two methods, method1 uses ++x and method2 uses x += 1:

   static void method1()
    {
        int x = 1;
        int y = ++x;

        Console.WriteLine(x);
        Console.WriteLine(y);
    }

    static void method2()
    {
        int x = 1;
        int y = x += 1;

        Console.WriteLine(x);
        Console.WriteLine(y);
    }

This produces the following IL:

Method 1:

enter image description here

Method 2:

enter image description here

There appears to be some minor differences, but my understanding of IL isn't enough to answer the question 'are there any differences'.

1

There are 1 answers

2
Jason W On

No difference at all. The Intermediate Language translated from x += 1 and x++ is identical:

int x = 0;
x++; // or x += 1;

The IL code is:

IL_0001:  ldc.i4.0    
IL_0002:  stloc.0     // x
IL_0003:  ldloc.0     // x
IL_0004:  ldc.i4.1    
IL_0005:  add         
IL_0006:  stloc.0     // x