In C# what is the difference between myInt++ and ++myInt?

后端 未结 11 1824
我寻月下人不归
我寻月下人不归 2020-12-06 03:11

I\'m having a hard time understanding what the difference is between incrementing a variable in C# this way:

myInt++;

and

         


        
11条回答
  •  粉色の甜心
    2020-12-06 03:25

    Others have shown where it makes a difference, and have commented that as a single statement it doesn't make a difference.

    I'd like to add that it's almost always a bad idea to use it where it makes a difference. I suspect there may be some times where it's more readable to have code such as:

    Console.WriteLine("Foo: {0}", foo++);
    

    than:

    Console.WriteLine("Foo: {0}", foo);
    foo++;
    

    ... but they're very rare! The latter of these two samples makes the ordering crystal clear immediately - the former requires a bit of thinking (to my poor brain, anyway). Think of the readability first.

提交回复
热议问题