This is my very first blog on C-Sharp Corner. Wanted to start with a little magic/surprising behavior of Increment Operators in C#. Refer below the code snippet, you'll find it interesting:
- class Program
- {
- static void Main(string[] args)
- {
- int x=1;
- int y = 0;
- y = x++;
- Console.WriteLine("X:=>{0},Y:=>{1}", x, y);
- Console.WriteLine();
- y = ++x;
- Console.WriteLine("X:=>{0},Y:=>{1}", x, y);
- Console.WriteLine();
- Console.WriteLine("X:=>{0},Y:=>{1}", x++, ++y);
- Console.WriteLine();
- Console.WriteLine("X:=>{0},Y:=>{1}", ++x, y++);
- Console.WriteLine();
- Console.WriteLine("X:=>{0},Y:=>{1}", x, y);
- Console.WriteLine();
- Console.Read();
- }
- }
It's good to check your knowledge by predicting the results before referring the answers. Below section contains the answers ready for you:
The output of the above snippet would be:
X:=>2,Y:=>1
X:=>3,Y:=>3
X:=>3,Y:=>4
X:=>5,Y:=>4
X:=>5,Y:=>5