- •Foreword
- •Introduction
- •Scope
- •Conformance
- •Normative references
- •Definitions
- •Notational conventions
- •Acronyms and abbreviations
- •General description
- •Language overview
- •Getting started
- •Types
- •Predefined types
- •Conversions
- •Array types
- •Type system unification
- •Variables and parameters
- •Automatic memory management
- •Expressions
- •Statements
- •Classes
- •Constants
- •Fields
- •Methods
- •Properties
- •Events
- •Operators
- •Indexers
- •Instance constructors
- •Destructors
- •Static constructors
- •Inheritance
- •Static classes
- •Partial type declarations
- •Structs
- •Interfaces
- •Delegates
- •Enums
- •Namespaces and assemblies
- •Versioning
- •Extern Aliases
- •Attributes
- •Generics
- •Why generics?
- •Creating and consuming generics
- •Multiple type parameters
- •Constraints
- •Generic methods
- •Anonymous methods
- •Iterators
- •Lexical structure
- •Programs
- •Grammars
- •Lexical grammar
- •Syntactic grammar
- •Grammar ambiguities
- •Lexical analysis
- •Line terminators
- •Comments
- •White space
- •Tokens
- •Unicode escape sequences
- •Identifiers
- •Keywords
- •Literals
- •Boolean literals
- •Integer literals
- •Real literals
- •Character literals
- •String literals
- •The null literal
- •Operators and punctuators
- •Pre-processing directives
- •Conditional compilation symbols
- •Pre-processing expressions
- •Declaration directives
- •Conditional compilation directives
- •Diagnostic directives
- •Region control
- •Line directives
- •Pragma directives
- •Basic concepts
- •Application startup
- •Application termination
- •Declarations
- •Members
- •Namespace members
- •Struct members
- •Enumeration members
- •Class members
- •Interface members
- •Array members
- •Delegate members
- •Member access
- •Declared accessibility
- •Accessibility domains
- •Protected access for instance members
- •Accessibility constraints
- •Signatures and overloading
- •Scopes
- •Name hiding
- •Hiding through nesting
- •Hiding through inheritance
- •Namespace and type names
- •Unqualified name
- •Fully qualified names
- •Automatic memory management
- •Execution order
- •Types
- •Value types
- •The System.ValueType type
- •Default constructors
- •Struct types
- •Simple types
- •Integral types
- •Floating point types
- •The decimal type
- •The bool type
- •Enumeration types
- •Reference types
- •Class types
- •The object type
- •The string type
- •Interface types
- •Array types
- •Delegate types
- •Boxing and unboxing
- •Boxing conversions
- •Unboxing conversions
- •Variables
- •Variable categories
- •Static variables
- •Instance variables
- •Instance variables in classes
- •Instance variables in structs
- •Array elements
- •Value parameters
- •Reference parameters
- •Output parameters
- •Local variables
- •Default values
- •Definite assignment
- •Initially assigned variables
- •Initially unassigned variables
- •Precise rules for determining definite assignment
- •General rules for statements
- •Block statements, checked, and unchecked statements
- •Expression statements
- •Declaration statements
- •If statements
- •Switch statements
- •While statements
- •Do statements
- •For statements
- •Break, continue, and goto statements
- •Throw statements
- •Return statements
- •Try-catch statements
- •Try-finally statements
- •Try-catch-finally statements
- •Foreach statements
- •Using statements
- •Lock statements
- •General rules for simple expressions
- •General rules for expressions with embedded expressions
- •Invocation expressions and object creation expressions
- •Simple assignment expressions
- •&& expressions
- •|| expressions
- •! expressions
- •?: expressions
- •Anonymous method expressions
- •Yield statements
- •Variable references
- •Atomicity of variable references
- •Conversions
- •Implicit conversions
- •Identity conversion
- •Implicit numeric conversions
- •Implicit enumeration conversions
- •Implicit reference conversions
- •Boxing conversions
- •Implicit type parameter conversions
- •Implicit constant expression conversions
- •User-defined implicit conversions
- •Explicit conversions
- •Explicit numeric conversions
- •Explicit enumeration conversions
- •Explicit reference conversions
- •Unboxing conversions
- •User-defined explicit conversions
- •Standard conversions
- •Standard implicit conversions
- •Standard explicit conversions
- •User-defined conversions
- •Permitted user-defined conversions
- •Evaluation of user-defined conversions
- •User-defined implicit conversions
- •User-defined explicit conversions
- •Anonymous method conversions
- •Method group conversions
- •Expressions
- •Expression classifications
- •Values of expressions
- •Operators
- •Operator precedence and associativity
- •Operator overloading
- •Unary operator overload resolution
- •Binary operator overload resolution
- •Candidate user-defined operators
- •Numeric promotions
- •Unary numeric promotions
- •Binary numeric promotions
- •Member lookup
- •Base types
- •Function members
- •Argument lists
- •Overload resolution
- •Applicable function member
- •Better function member
- •Better conversion
- •Function member invocation
- •Invocations on boxed instances
- •Primary expressions
- •Literals
- •Simple names
- •Invariant meaning in blocks
- •Parenthesized expressions
- •Member access
- •Identical simple names and type names
- •Invocation expressions
- •Method invocations
- •Delegate invocations
- •Element access
- •Array access
- •Indexer access
- •This access
- •Base access
- •Postfix increment and decrement operators
- •The new operator
- •Object creation expressions
- •Array creation expressions
- •Delegate creation expressions
- •The typeof operator
- •The checked and unchecked operators
- •Default value expression
- •Anonymous methods
- •Anonymous method signatures
- •Anonymous method blocks
- •Outer variables
- •Captured outer variables
- •Instantiation of local variables
- •Anonymous method evaluation
- •Implementation example
- •Unary expressions
- •Unary plus operator
- •Unary minus operator
- •Logical negation operator
- •Bitwise complement operator
- •Prefix increment and decrement operators
- •Cast expressions
- •Arithmetic operators
- •Multiplication operator
- •Division operator
- •Remainder operator
- •Addition operator
- •Subtraction operator
- •Shift operators
- •Relational and type-testing operators
- •Integer comparison operators
- •Floating-point comparison operators
- •Decimal comparison operators
- •Boolean equality operators
- •Enumeration comparison operators
- •Reference type equality operators
- •String equality operators
- •Delegate equality operators
- •The is operator
- •The as operator
- •Logical operators
- •Integer logical operators
- •Enumeration logical operators
- •Boolean logical operators
- •Conditional logical operators
- •Boolean conditional logical operators
- •User-defined conditional logical operators
- •Conditional operator
- •Assignment operators
- •Simple assignment
- •Compound assignment
- •Event assignment
- •Expression
- •Constant expressions
- •Boolean expressions
- •Statements
- •End points and reachability
- •Blocks
- •Statement lists
- •The empty statement
- •Labeled statements
- •Declaration statements
- •Local variable declarations
- •Local constant declarations
- •Expression statements
- •Selection statements
- •The if statement
- •The switch statement
- •Iteration statements
- •The while statement
- •The do statement
- •The for statement
- •The foreach statement
- •Jump statements
- •The break statement
- •The continue statement
- •The goto statement
- •The return statement
- •The throw statement
- •The try statement
- •The checked and unchecked statements
- •The lock statement
- •The using statement
- •The yield statement
- •Namespaces
- •Compilation units
- •Namespace declarations
- •Extern alias directives
- •Using directives
- •Using alias directives
- •Using namespace directives
- •Namespace members
- •Type declarations
- •Qualified alias member
- •Classes
- •Class declarations
- •Class modifiers
- •Abstract classes
- •Sealed classes
- •Static classes
- •Class base specification
- •Base classes
- •Interface implementations
- •Class body
- •Partial declarations
- •Class members
- •Inheritance
- •The new modifier
- •Access modifiers
- •Constituent types
- •Static and instance members
- •Nested types
- •Fully qualified name
- •Declared accessibility
- •Hiding
- •this access
- •Reserved member names
- •Member names reserved for properties
- •Member names reserved for events
- •Member names reserved for indexers
- •Member names reserved for destructors
- •Constants
- •Fields
- •Static and instance fields
- •Readonly fields
- •Using static readonly fields for constants
- •Versioning of constants and static readonly fields
- •Volatile fields
- •Field initialization
- •Variable initializers
- •Static field initialization
- •Instance field initialization
- •Methods
- •Method parameters
- •Value parameters
- •Reference parameters
- •Output parameters
- •Parameter arrays
- •Static and instance methods
- •Virtual methods
- •Override methods
- •Sealed methods
- •Abstract methods
- •External methods
- •Method body
- •Method overloading
- •Properties
- •Static and instance properties
- •Accessors
- •Virtual, sealed, override, and abstract accessors
- •Events
- •Field-like events
- •Event accessors
- •Static and instance events
- •Virtual, sealed, override, and abstract accessors
- •Indexers
- •Indexer overloading
- •Operators
- •Unary operators
- •Binary operators
- •Conversion operators
- •Instance constructors
- •Constructor initializers
- •Instance variable initializers
- •Constructor execution
- •Default constructors
- •Private constructors
- •Optional instance constructor parameters
- •Static constructors
- •Destructors
- •Structs
- •Struct declarations
- •Struct modifiers
- •Struct interfaces
- •Struct body
- •Struct members
- •Class and struct differences
- •Value semantics
- •Inheritance
- •Assignment
- •Default values
- •Boxing and unboxing
- •Meaning of this
- •Field initializers
- •Constructors
- •Destructors
- •Static constructors
- •Struct examples
- •Database integer type
- •Database boolean type
- •Arrays
- •Array types
- •The System.Array type
- •Array creation
- •Array element access
- •Array members
- •Array covariance
- •Arrays and the generic IList interface
- •Array initializers
- •Interfaces
- •Interface declarations
- •Interface modifiers
- •Base interfaces
- •Interface body
- •Interface members
- •Interface methods
- •Interface properties
- •Interface events
- •Interface indexers
- •Interface member access
- •Fully qualified interface member names
- •Interface implementations
- •Explicit interface member implementations
- •Interface mapping
- •Interface implementation inheritance
- •Interface re-implementation
- •Abstract classes and interfaces
- •Enums
- •Enum declarations
- •Enum modifiers
- •Enum members
- •The System.Enum type
- •Enum values and operations
- •Delegates
- •Delegate declarations
- •Delegate instantiation
- •Delegate invocation
- •Exceptions
- •Causes of exceptions
- •The System.Exception class
- •How exceptions are handled
- •Common Exception Classes
- •Attributes
- •Attribute classes
- •Attribute usage
- •Positional and named parameters
- •Attribute parameter types
- •Attribute specification
- •Attribute instances
- •Compilation of an attribute
- •Run-time retrieval of an attribute instance
- •Reserved attributes
- •The AttributeUsage attribute
- •The Conditional attribute
- •Conditional Methods
- •Conditional Attribute Classes
- •The Obsolete attribute
- •Unsafe code
- •Unsafe contexts
- •Pointer types
- •Fixed and moveable variables
- •Pointer conversions
- •Pointers in expressions
- •Pointer indirection
- •Pointer member access
- •Pointer element access
- •The address-of operator
- •Pointer increment and decrement
- •Pointer arithmetic
- •Pointer comparison
- •The sizeof operator
- •The fixed statement
- •Stack allocation
- •Dynamic memory allocation
- •Generics
- •Generic class declarations
- •Type parameters
- •The instance type
- •Members of generic classes
- •Static fields in generic classes
- •Static constructors in generic classes
- •Accessing protected members
- •Overloading in generic classes
- •Parameter array methods and type parameters
- •Overriding and generic classes
- •Operators in generic classes
- •Nested types in generic classes
- •Generic struct declarations
- •Generic interface declarations
- •Uniqueness of implemented interfaces
- •Explicit interface member implementations
- •Generic delegate declarations
- •Constructed types
- •Type arguments
- •Open and closed types
- •Base classes and interfaces of a constructed type
- •Members of a constructed type
- •Accessibility of a constructed type
- •Conversions
- •Using alias directives
- •Generic methods
- •Generic method signatures
- •Virtual generic methods
- •Calling generic methods
- •Inference of type arguments
- •Using a generic method with a delegate
- •Constraints
- •Satisfying constraints
- •Member lookup on type parameters
- •Type parameters and boxing
- •Conversions involving type parameters
- •Iterators
- •Iterator blocks
- •Enumerator interfaces
- •Enumerable interfaces
- •Yield type
- •This access
- •Enumerator objects
- •The MoveNext method
- •The Current property
- •The Dispose method
- •Enumerable objects
- •The GetEnumerator method
- •Implementation example
- •Lexical grammar
- •Line terminators
- •White space
- •Comments
- •Unicode character escape sequences
- •Identifiers
- •Keywords
- •Literals
- •Operators and punctuators
- •Pre-processing directives
- •Syntactic grammar
- •Basic concepts
- •Types
- •Expressions
- •Statements
- •Classes
- •Structs
- •Arrays
- •Interfaces
- •Enums
- •Delegates
- •Attributes
- •Generics
- •Grammar extensions for unsafe code
- •Undefined behavior
- •Implementation-defined behavior
- •Unspecified behavior
- •Other Issues
- •Capitalization styles
- •Pascal casing
- •Camel casing
- •All uppercase
- •Capitalization summary
- •Word choice
- •Namespaces
- •Classes
- •Interfaces
- •Enums
- •Static fields
- •Parameters
- •Methods
- •Properties
- •Events
- •Case sensitivity
- •Avoiding type name confusion
- •Documentation Comments
- •Introduction
- •Recommended tags
- •<code>
- •<example>
- •<exception>
- •<list>
- •<para>
- •<param>
- •<paramref>
- •<permission>
- •<remarks>
- •<returns>
- •<seealso>
- •<summary>
- •<value>
- •Processing the documentation file
- •ID string format
- •ID string examples
- •An example
- •C# source code
- •Resulting XML
Chapter 14 Expressions
114.13 Assignment operators
2The assignment operators assign a new value to a variable, a property, event, or an indexer element.
3assignment:
4 |
unary-expression assignment-operator expression |
5 |
assignment-operator: one of |
6 |
= += -= *= /= %= &= |= ^= <<= right-shift-assignment |
7The left operand of an assignment shall be an expression classified as a variable, a property access, an
8indexer access, or an event access.
9The = operator is called the simple assignment operator. It assigns the value of the right operand to the
10variable, property, or indexer element given by the left operand. The left operand of the simple assignment
11operator shall not be an event access (except as described in §17.7.1). The simple assignment operator is
12described in §14.13.1.
13The operators formed by prefixing an = character with a binary operator are called the compound
14assignment operators. These operators perform the indicated operation on the two operands, and then
15assign the resulting value to the variable, property, or indexer element given by the left operand. The
16compound assignment operators are described in §14.13.2.
17The += and -= operators with an event access expression as the left operand are called the event
18assignment operators. No other assignment operator is valid with an event access as the left operand. The
19event assignment operators are described in §14.13.3.
20The assignment operators are right-associative, meaning that operations are grouped from right to left.
21 [Example: An expression of the form a = b = c is evaluated as a = (b = c). end example]
2214.13.1 Simple assignment
23The = operator is called the simple assignment operator. In a simple assignment, the right operand shall be
24an expression of a type that is implicitly convertible to the type of the left operand. The operation assigns the
25value of the right operand to the variable, property, or indexer element given by the left operand.
26The result of a simple assignment expression is the value assigned to the left operand. The result has the
27same type as the left operand and is always classified as a value.
28If the left operand is a property or indexer access, the property or indexer shall have a set accessor. If this is
29not the case, a compile-time error occurs.
30The run-time processing of a simple assignment of the form x = y consists of the following steps:
31• If x is classified as a variable:
32o x is evaluated to produce the variable.
33o y is evaluated and, if required, converted to the type of x through an implicit conversion (§13.1).
34o If the variable given by x is an array element of a reference-type, a run-time check is performed to
35ensure that the value computed for y is compatible with the array instance of which x is an element.
36The check succeeds if y is null, or if an implicit reference conversion (§13.1.4) exists from the
37actual type of the instance referenced by y to the actual element type of the array instance containing
38x. Otherwise, a System.ArrayTypeMismatchException is thrown.
39o The value resulting from the evaluation and conversion of y is stored into the location given by the
40evaluation of x.
41• If x is classified as a property or indexer access:
42o The instance expression (if x is not static) and the argument list (if x is an indexer access)
43associated with x are evaluated, and the results are used in the subsequent set accessor invocation.
44o y is evaluated and, if required, converted to the type of x through an implicit conversion (§13.1).
209
C# LANGUAGE SPECIFICATION
1o The set accessor of x is invoked with the value computed for y as its value argument.
2[Note: The array covariance rules (§19.5) permit a value of an array type A[] to be a reference to an
3instance of an array type B[], provided an implicit reference conversion exists from B to A. Because of
4these rules, assignment to an array element of a reference-type requires a run-time check to ensure that the
5value being assigned is compatible with the array instance. In the example
6string[] sa = new string[10];
7object[] oa = sa;
8 |
oa[0] = null; |
// Ok |
9 |
oa[1] = "Hello"; |
// Ok |
10 |
oa[2] = new ArrayList(); |
// ArrayTypeMismatchException |
11the last assignment causes a System.ArrayTypeMismatchException to be thrown because an instance
12of ArrayList cannot be stored in an element of a string[]. end note]
13When a property or indexer declared in a struct-type is the target of an assignment, the instance expression
14associated with the property or indexer access shall be classified as a variable. If the instance expression is
15classified as a value, a compile-time error occurs. [Note: Because of §14.5.4, the same rule also applies to
16fields. end note]
17[Example: Given the declarations:
18struct Point
19{
20 |
int x, |
y; |
21 |
public Point(int x, int y) { |
|
22 |
this.x = x; |
|
23 |
this.y = y; |
|
24 |
} |
|
25 |
public int X { |
|
26 |
get { return x; } |
|
27 |
set { x = value; } |
|
28 |
} |
|
29 |
public int Y { |
|
30 |
get { return y; } |
|
31 |
set { y = value; } |
|
32}
33}
34struct Rectangle
35{
36 |
Point a, b; |
37 |
public Rectangle(Point a, Point b) { |
38 |
this.a = a; |
39 |
this.b = b; |
40 |
} |
41 |
public Point A { |
42 |
get { return a; } |
43 |
set { a = value; } |
44 |
} |
45 |
public Point B { |
46 |
get { return b; } |
47 |
set { b = value; } |
48}
49}
50in the example
51Point p = new Point();
52p.X = 100;
53p.Y = 100;
54Rectangle r = new Rectangle();
55r.A = new Point(10, 10);
56r.B = p;
210
Chapter 14 Expressions
1the assignments to p.X, p.Y, r.A, and r.B are permitted because p and r are variables. However, in the
2example
3Rectangle r = new Rectangle();
4r.A.X = 10;
5r.A.Y = 10;
6r.B.X = 100;
7r.B.Y = 100;
8the assignments are all invalid, since r.A and r.B are not variables. end example]
914.13.2 Compound assignment
10An operation of the form x op= y is processed by applying binary operator overload resolution (§14.2.4) as
11if the operation was written x op y. Then,
12• If the return type of the selected operator is implicitly convertible to the type of x, the operation is
13evaluated as x = x op y, except that x is evaluated only once.
14• Otherwise, if the selected operator is a predefined operator, if the return type of the selected operator is
15explicitly convertible to the type of x, and if y is implicitly convertible to the type of x or the operator is
16a shift operator, then the operation is evaluated as x = (T)(x op y), where T is the type of x, except
17that x is evaluated only once.
18• Otherwise, the compound assignment is invalid, and a compile-time error occurs.
19The term “evaluated only once” means that in the evaluation of x op y, the results of any constituent
20expressions of x are temporarily saved and then reused when performing the assignment to x. [Example: In
21the assignment A()[B()] += C(), where A is a method returning int[], and B and C are methods returning
22int, the methods are invoked only once, in the order A, B, C. end example]
23When the left operand of a compound assignment is a property access or indexer access, the property or
24indexer shall have both a get accessor and a set accessor. If this is not the case, a compile-time error
25occurs.
26 The second rule above permits x op= y to be evaluated as x = (T)(x op y) in certain contexts. The rule
27exists such that the predefined operators can be used as compound operators when the left operand is of type
28sbyte, byte, short, ushort, or char. Even when both arguments are of one of those types, the
29predefined operators produce a result of type int, as described in §14.2.6.2. Thus, without a cast it would
30not be possible to assign the result to the left operand.
31The intuitive effect of the rule for predefined operators is simply that x op= y is permitted if both of
32x op y and x = y are permitted. [Example: In the following code
33byte b = 0;
34char ch = '\0';
35int i = 0;
36 |
b += 1; |
// Ok |
37 |
b += 1000; |
// Error, b = 1000 not permitted |
38 |
b += i; |
// Error, b = i not permitted |
39 |
b += (byte)i; |
// Ok |
40 |
ch += 1; |
// Error, ch = 1 not permitted |
41 |
ch += (char)1; |
// Ok |
42the intuitive reason for each error is that a corresponding simple assignment would also have been an error.
43end example]
4414.13.3 Event assignment
45If the left operand of a += or -= operator is classified as an event access, then the expression is evaluated as
46follows:
47• The instance expression, if any, of the event access is evaluated.
211
