C# Pre-Increment and Post-Increment Operator with Example




In this article, I am going to explain you, C# Pre-Increment and Post-Increment Operator with Example.

In C#, we can use, increment (++) or decrement (--) operators before and after the variable.

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

Here, value returned by i++ is value of (i) before the increment takes place and ++i is the value of i after the increment takes place.

C# Pre-Increment and Post-Increment Operator Example

Please refer below C# example to understand Pre and Post increment operator.

using System;
					
public class Program
{
	public static void Main()
	{
		// Post-increment example
		int a = 0;
		int b = a++;
		Console.WriteLine("Value of a: "+a);
		Console.WriteLine("Value of b: "+b);
		// In post-increment value of a is assigned to b before the increment take place
		
		Console.WriteLine();
		
		// Pre-increment example
		int i = 0;
		int j = ++i;
		Console.WriteLine("Value of i: " +i);
		Console.WriteLine("Value of j: " +j);
		// in pre-increment value of i is incremented first and then assigned to j
		
	}
}
OUTPUT:
Value of a: 1
Value of b: 0

Value of i: 1
Value of j: 1

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).

In similar way, you can use pre-decrement and post decrement operator.



Share This


blog comments powered by Disqus