For this first test you will see that there isn’t a difference, it is working differently, but you cannot tell the difference in this example:

public static void IncrementTest()
{ 
 Console.WriteLine("nn++i");
 for (int i = 0; i < 10; ++i)
 {
  Console.WriteLine(i);
 }

 Console.WriteLine("nni++");
 for (int i = 0; i < 10; i++)
 {  
  Console.WriteLine(i);
 } 
}

This next example highlights the differences between i++ and ++i.

public static void IncrementTest2()
{
 int i = 0;
 
 Console.WriteLine("Initial Value: {0}n", i);
 
 Console.WriteLine("Param i++ {0}", i++);
 Console.WriteLine("After Param i++ {0}n", i);

 i = 0;

 Console.WriteLine("Param ++i {0}", ++i);
 Console.WriteLine("After Param ++i {0}n", i);

 i = 0;
 i++;

 Console.WriteLine("Statement i++ {0}n", i);

 i = 0;
 ++i;

 Console.WriteLine("Statement ++i {0}n", i);
}

Conclusion, be careful when writing code, don’t assume that things work the same way when written differently.

Leave a Reply

Your email address will not be published. Required fields are marked *