C# - Prefix & Postfix Example

Pre-Increment and Post-Increment in C# with Example (++i & i++)

  • C#
  • 2 mins read

In C#, you can place the increment (++) and decrement (--) operators either before or after the variable. Putting the operator before the variable is called the prefix (pre-increment) and using the operator after the variable is called postfix (post-increment). Below are the examples:

i++; // post-increment (postfix)
++i; // pre-increment (prefix)
i--; // post-increment (postfix)
--i; // pre-increment (prefix)

Difference Between Pre-Increment and Post-Increment in C#

There is no difference whether you use prefix or postfix form; the variable value will increase by 1. Then you must be wondering why there are two ways to do the same thing. Here is the answer, the value returned by i++ is the value of (i) before the increment takes place, whereas the value returned by ++i is the value of (i) after the increment takes place. The following is an example:

using System;

class Hello
{
    static void Main(string[] args)
    {
        int i, j;
        // post-increment example
        i = 0;
        j = i++; 
        Console.WriteLine("The value of j (i++): " + j);
        Console.WriteLine("The value of i (i++): " + i);
        // pre-increment example
        i = 0;
        j = ++i; 
        Console.WriteLine("The value of j (++i): " + j);
        Console.WriteLine("The value of i (++i): " + i);
    }
}

Output

The value of j (i++): 0
The value of i (i++): 1
The value of j (++i): 1
The value of i (++i): 1
Press any key to continue . . .

You can remember in this way also, in the expression i++, the variable (i) comes first, so its value is used as the value of the expression before (i) is incremented. In the expression ++i, the operator comes first, so its operation is performed before the value of (i).

See also: