C# Preincrement Integers

Int keyword

A number is incremented with an operator. Two increment operators in the C# language are postincrement and preincrement. They have different meanings. It is important to choose the correct one for your program.

Notes: Preincrement: ++i
Postincrement: i++
You can sometimes combine assignments with preincrements. This can improve performance.

Increment int

First, we look at the postincrement operator. You should be very familiar with the double-plus and double-minus operators. This post is about a less common use of these operators. This example shows how you can use the two pluses at the end of the variable identifier to increment the integer.

Program that increments [C#]

class Program
{
    static int _x;

    static void Main()
    {
	// Add one.
	_x++;

	// Read in the value again.
	int count = _x;
    }
}

Preincrement example

Here we look at how you can preincrement an integer. There are some cases when accessing an integer is relatively slow. This can be the case with static variables and volatile member ints. Here's how you can use preincrement to do the same thing.

Program that increments [C#]

class Program
{
    static int _x;

    static void Main()
    {
	// Increment then assign.
	int count = ++_x;
    }
}

Benchmark

Here we look at a benchmark of the two versions of the code. What I found is that when all variables are easy to "optimize" for the compiler, there is no difference. If your int is another class, it's slower to use.

Lines of code in benchmark

//
// 1.
//
TestStatic._test++;
int z = TestStatic._test;

//
// 2.
//
int z = ++TestStatic._test;

Benchmark results

Method 1 postincrement: 3026 ms
Method 2 preincrement:  2574 ms

Performance

Performance optimization

You may be wondering if there is a performance difference between having the ++ or -­- at the start or end. Some programmers have said that preincrementing is faster than postincrementing, but I was unable to reproduce this. I understand that this comes from C++ and some old implementations of it.

Summary

The C# programming language

Here we saw how you can pre-increment and post-increment integers in your C# program. Combine increments and assigns in your C# programs. The compiler is unable to optimize for static members, so this is substantially more efficient. Use the preincrement-assign pattern for better performance. You can find more general information on incrementing integers here.

Increment Int Number Examples
.NET