Wednesday, 21 November 2018

Prefix and Postfix in .NET explained in 1 minute

Using prefix in comparison will change the value before expression evaluation, where using postfix will change value after expression evaluation. Look at below example.

public static void Main()
 {
  // Prefix and Postfix example
  
  int x = 5;
  if(++x == 6)
  {
   Console.WriteLine("Using prefix will increment value before expression is evaluated.");
  }
  
  Console.WriteLine(string.Format("Value of x is {0}", x));
  if(x++ == 7)
  {
   // we will never reach this code as expression is evaluated before increment, hence x is still equal to 6
   Console.WriteLine("I am here but you will never see me in console.");
  }
  
  Console.WriteLine(string.Format("Value of x is {0}", x));
 }

You can look into example in dotnetfiddle - https://dotnetfiddle.net/txxcEa