0

What's the difference between postfix and prefix in C#?

I didn't quite understand what the difference between a prefix (f.e: ++i) and postfix (f.e i++) is. Can someone please in detail explain what the differences are, and how it would affect a value?

6th Jun 2019, 9:07 PM
Ivaylo Valchev
Ivaylo Valchev - avatar
5 Answers
+ 15
• Increment and Decrement Operators The increment and decrement operators (++, --) increment and decrement numeric types by 1. The operator can either precede or follow the variable, depending on whether you want the variable to be updated 'before' or 'after' the expression is evaluated. For example:     int x = 0; Console.WriteLine(x++); // Outputs 0; x is now 1 Console.WriteLine(++x); // Outputs 2; x is now 2 Console.WriteLine(--x);   // Outputs 1; x is now 1 D_Stark Thank you!😊 • https://code.sololearn.com/cCEWmvfjC837/?ref=app
6th Jun 2019, 11:26 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 16
Ivaylo Valchev [ ++i and i++ both add 1 to i ] However, ++i returns the new value, and i++ returns the old value. Likewise for decrement, --i and i--, which subtracts 1. An easy way to remember how these operators behave involves these two rules: • If the operator appears 'before' the operand, the operation will occur 'before' the expression has been evaluated.   • If the operator appears 'after' the operand, the operation will occur 'after' the expression has already been evaluated.
6th Jun 2019, 11:35 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 13
Ivaylo Valchev You should check out the comments in the lesson — https://www.sololearn.com/learn/CSharp/2590/ You will find excellent explanation!👍
7th Jun 2019, 10:45 AM
Danijel Ivanović
Danijel Ivanović - avatar
6th Jun 2019, 9:40 PM
D_Stark
D_Stark - avatar
+ 1
D_Stark Thanks, this was greatly explained :)
6th Jun 2019, 10:05 PM
Ivaylo Valchev
Ivaylo Valchev - avatar