Search code examples
c#returnauto-increment

C# Return statement with auto-increment value


Is there a reason why these 2 examples do not produce the same value. C # doesn't seem to auto-increment before returning.

        nextNumber++;
        return nextNumber;

and

 return nextNumber++;

Is it a bug? I am using Microsoft Visual Studio Community 2019 Version 16.7.6


Solution

  • Nope, check this out:

    using System;
                        
    public class Program
    {
        public static void Main()
        {
            Console.WriteLine(t1(1));
            Console.WriteLine(t2(1));
            Console.WriteLine(t3(1));
        }
        
        private static int  t1(int nextNumber)
        {
             return nextNumber++;       
        }
        
        private static int  t2(int nextNumber)
        {
            nextNumber++;
            return nextNumber;  
        }
        
        private static int t3(int nextNumber)
        {
            return ++nextNumber;    
        }
    }
    

    https://dotnetfiddle.net/4fna9w

    outputs:

    1
    2
    2
    

    See: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators#increment-operator-

    the postfix increment operator, x++, and the prefix increment operator, ++x.

    Check the examples on the doc.