The Quick start tells you how to use arithmetic operators to create new values. For example, the following statement uses the operator + to create a value that is 42 larger than the variable answer, and the new value is written to the console:
Console.WriteLine (answer + 42);
I've also talked about how to use assignment statements to change the value of a variable. The following statement uses the assignment operator to change the value of the answer to 42:
Answer = 42;
If you want to add 42 to the value of a variable, you can match the assignment operator with the addition operation. For example, the following statement adds 42 to the answer and assigns the new value to answer. In other words, after the statement is run, the value of answer will be 42 larger than before:
Answer = answer + 42;
Although this is a valid statement, it is not written by experienced programmers. Adding a value to a variable is a very common operation, so Microsoft Visual C # specifically provides a composite assignment operator = = To simplify this operation. To add 42 to the answer, an experienced programmer would write:
Answer + 42;
With this shortcut, you can match any arithmetic operator with an assignment operation, as summarized in table 5.1. These operations are called compound assignment operators (compound assignment operator) Fu Shi.
Table 5.1 Compound assignment operators
Wrong wording |
Correct wording |
variable = variable * number; |
Variable *= number; |
variable = variable/number; |
Variable/= number; |
variable = variable%; |
Variable%= number; |
variable = variable + number; |
Variable + = number; |
variable = variable-number; |
variable = number; |
Tip The compound assignment operator has the same priority and right associativity as the simple assignment operator.
The operator + + can also be used for strings; it can append a string to the end of another string. For example, the following code will display "Hello John" on the console:
String name = "John";
String greeting = "Hello";
Greeting + = name;
Console.WriteLine (greeting);
However, you cannot use any of the other compound assignment operators on strings.
Note that you need to increment or decrement a variable by 1 o'clock instead of using the compound assignment operator, rather than using the operator + + and the--。 For example, the following statement is written incorrectly:
Count + 1;
The correct wording is as follows:
count++;