Banana Banana - 2 months ago 10
C# Question

Why the increment of an integer on C# is executed after a function return its value?

Why this two functions return different values?

When I call this function passing 0 as parameter it returns 1

public static int IncrementByOne(int number)
{
return (number + 1);
}


However, when I call this function passing 0 as parameter it returns 0 even though the increment is executed and the number variable changes its value to 1 inside the method?

public static int IncrementByOne(int number)
{
return number++;
}


What is the reason why the returned values of this two functions are different?

Answer

number++ is a postincrement. It returns its current value before it is incremented. To get the same behaviour as in your first method, use a preincrement ++number

See documentation: https://msdn.microsoft.com/en-us/library/36x43w8w.aspx

Comments