0

This is my test code,it's very simple:

  class Program
    {
        static void Main(string[] args)
        {
            int number = 0;
            int newNumber = number++;
            Console.WriteLine("the old number is {0},the new number is:{1}", number, newNumber);
            Console.Read();
        }
    }

whereas the output result is:'the old number is 1,the new number is:0',I think it's opposite with the result I want.

1
  • 3
    It just so happens Microsoft writes documentation about its language features. Before asking a question, make sure you have taken the time to read the documentation, it will make your jedi programming journey a lot smoother learn.microsoft.com/en-us/dotnet/csharp/language-reference/… Commented Jun 18, 2020 at 1:19

3 Answers 3

3

using the postfix increment ++ operator, it first returns the original value, then increments. To get what you want use the prefix increment operator like

 int newNumber = ++number;

But if you don't want to change number, don't use an incrementing operator, use addition/subtraction instead.

Sign up to request clarification or add additional context in comments.

Comments

2

That is because number++ updates the value of number by incrementing it (PostFix). This is done after using the original value in the expression it is used. To achieve the desired behaviour, You can use:

int number = 0;
int newNumber = number + 1;

Comments

1

Here, you have used number++ which is Post increment operator. It assigns the value first and then increments its value. You can achieve your desired output in two ways :

  1. Use Pre increment operator

    int newNumber = ++number;

  2. Simply adding 1 to number variable and then assigning it to newNumber

    int newNumber = number + 1;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.