C # Assignment operators and assignment expressions

Source: Internet
Author: User

Assignment is to assign a new value to a variable. The assignment expressions provided in C # are:

= + = = *=/=%= &=/= ^= <<= >>=

The left operand of an assignment must be an expression of a variable, a property accessor, or an index accessor.

In C #, variables can be assigned sequentially, and the assignment operator is right associated, which means that the right-to-left operators are grouped. For example, an expression like a=b=c is equivalent to A= (b=c).

If the operand types on either side of the assignment operator are inconsistent, type conversion is the first.

7.3.1 Simple Assignment

The "=" operator is called a simple assignment operator. In a simple assignment, the right-hand operand must be an expression of some type, and the type must be implicitly convertible to the left operand type. This operator assigns the value of the right-hand operand to the variable, property, or indexer type as the left operand. The result of a simple assignment expression is the value assigned to the left operand. The result type is the same type as the left operand and is always a value type.

7.3.2 Compound Assignment

Operations such as X-op=y can handle the overloaded method of binary operators that form x op y. Like what:

x+=5; equals x=x+5

x%=3; equals x=x%3

x*=y+1; equals x=x* (y+1)

The steps for compound assignment are as follows:

(1) If the return type of the selected operator can be implicitly converted to the data type of x, perform the operation of x=x op y and, in addition, perform an operation on X only.

(2) Otherwise, the selected operator is a predefined operator, and the return value type of the selected operator can be explicitly converted to the type of X. and y can be implicitly converted to the type of x, then the operation is equivalent to the x= (t) (x op y) operation, where T is the type of x, except that x is executed once.

(3) Otherwise, the compound assignment is invalid and produces a compile-time error.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.