The increment operator + + adds 1 to the value of the variable, while the decrement operator--slows the value of the variable by 1. They are suitable for sbyte,byte,short,ushort,int,uint,long,ulong,char,float,double,decimal and any type of enum. For example, assuming that the value of an integer x is 9, then the value after X + + is 10.
Note: The operands of the self-increment and decrement operators must be a variable, a property accessor, or an index indicator accessor, not a constant or other expression. 5++ and (x+), for example, are illegal. If the operand is an accessor, then the accessor must support both read and write.
The self-increment and decrement operators also have a prefix. For the prefix operator, followed by the principle of "first increase or decrease, after use", the suffix operator is just the opposite, is "first use, after the increase or decrease." We use examples to illustrate this problem.
Program Listing 7-7:
Using System;
Class Test
{public
static void Main () {
int x=5;
int y=x++;
Console.WriteLine (y);
y=++x;
Console.WriteLine (y);
}
}
The first time is to use after the addition, so the output is 5, the second first added after the use, the output is 7.
Look at one more example.
Program Listing 7-8:
Using System;
Class Test
{public
static void Main () {
int x=5;
Console.WriteLine (x + +) + (x + +) + (x + +));
int y= (x + +) + (x + +) + (x + +);
Console.WriteLine (y);
}
}
The results of the program running are:
18
27
Readers may find it difficult to understand the results of the output. In fact, the process of compiling is this: The compiler first scans the entire expression, first the X's original value out, the expression solution, and then for each x to perform the + + operation.