
- •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
1An anonymous-method-expression can be used in a delegate-creation-expression (§14.5.10.3). All other
2valid uses of an anonymous-method-expression depend on the implicit conversions defined in §13.5.
3An anonymous-method-expression defines a new declaration space for parameters, locals and constants and
4a new declaration space for labels (§10.3).
514.5.14.1 Anonymous method signatures
6The optional anonymous-method-signature defines the names and types of the formal parameters for the
7anonymous method. The scope of the parameters of the anonymous method is the block. It is a compile-time
8error for the name of a parameter of the anonymous method to match the name of a local variable, local
9constant or parameter whose scope includes the anonymous-method-expression.
10If an anonymous-method-expression has an anonymous-method-signature, then the set of compatible
11delegate types is restricted to those that have the same parameter types and modifiers, in the same order
12(§13.5). In constrast to method groups, contra-variance of anonymous method parameter types is not
13supported (§14.5.10.3). If an anonymous-method-expression doesn’t have an anonymous-method-signature,
14then the set of compatible delegate types is restricted to those that have no out parameters.
15Note that an anonymous-method-signature cannot include attributes or a parameter-array. Nevertheless, an
16anonymous-method-signature may be compatible with a delegate type whose formal-parameter-list contains
17a parameter-array.
1814.5.14.2 Anonymous method blocks
19The block of an anonymous-method-expression is subject to the following rules:
20• If the anonymous method includes a signature, the parameters specified in the signature are available in
21the block. If the anonymous method has no signature, it can be converted to a delegate type having
22parameters (§13.5), but the parameters cannot be accessed in the block.
23• Except for ref or out parameters specified in the signature (if any) of the nearest enclosing anonymous
24method, it is a compile-time error for the block to access a ref or out parameter.
25• When the type of this is a struct type, it is a compile-time error for the block to access this. This is
26true whether the access is explicit (as in this.x) or implicit (as in x, where x is an instance member of
27the struct). This rule simply prohibits such access and does not affect whether member lookup results in
28a member of the struct.
29• The block has access to the outer variables (§14.5.14.3) of the anonymous method. Access of an outer
30variable will reference the instance of the variable that is active at the time the anonymous-method-
31expression is evaluated (§14.5.14.4).
32• It is a compile-time error for the block to contain a goto statement, break statement, or continue
33statement whose target is outside the block or within the block of a contained anonymous method.
34• A return statement in the block returns control from an invocation of the nearest enclosing anonymous
35method, not from the enclosing function member. An expression specified in a return statement shall
36be compatible with the delegate type to which the nearest enclosing anonymous-method-expression is
37converted (§14.5.14.4).
38It is explicitly unspecified whether there is any way to execute the block of an anonymous method other than
39through evaluation and invocation of the anonymous-method-expression. In particular, a compiler might
40choose to implement an anonymous method by synthesizing one or more named methods or types. The
41names of any such synthesized elements shall be in the space reserved for implementations (that is, the
42names shall contain two consecutive underscore characters).
4314.5.14.3 Outer variables
44Any local variable, value parameter, or parameter array whose scope includes an anonymous-method-
45expression is called an outer variable of that anonymous-method-expression. In an instance function
181
C# LANGUAGE SPECIFICATION
1member of a class, the this value is considered a value parameter and is an outer variable of any
2anonymous-method-expression contained within that function member.
314.5.14.3.1 Captured outer variables
4When an outer variable is referenced by an anonymous method, the outer variable is said to have been
5captured by the anonymous method. Ordinarily, the lifetime of a local variable is limited to execution of the
6block or statement with which it is associated (§12.1.7). However, the lifetime of a captured outer variable is
7extended at least until the delegate referring to the anonymous method becomes eligible for garbage
8collection.
9[Example: In the following code
10using System;
11delegate int D();
12class Test
13{
14 |
static D F() { |
15 |
int x = 0; |
16 |
D result = delegate { return ++x; }; |
17 |
return result; |
18 |
} |
19 |
static void Main() { |
20 |
D d = F(); |
21 |
Console.WriteLine(d()); |
22 |
Console.WriteLine(d()); |
23 |
Console.WriteLine(d()); |
24}
25}
26the local variable x is captured by the anonymous method, and the lifetime of x is extended at least until the
27delegate returned from F becomes eligible for garbage collection. Since each invocation of the anonymous
28method operates on the same instance of x, the output of the example is:
291
302
313
32end example]
3314.5.14.3.2 Instantiation of local variables
34A local variable is considered to be instantiated when execution enters the scope of the variable. [Example:
35When the following method is invoked, the local variable x is instantiated and initialized three times—once
36each iteration of the loop.
37static void F() {
38 |
for (int i = 0; i < 3; i++) { |
39 |
int x = i * 2 + 1; |
40 |
… |
41}
42}
43However, moving the declaration of x outside the loop results in a single instantiation of x:
44static void F() {
45 |
int x; |
46 |
for (int i = 0; i < 3; i++) { |
47 |
x = i * 2 + 1; |
48 |
… |
49}
50}
51end example]
182
Chapter 14 Expressions
1Ordinarily, there is no way to observe exactly how often a local variable is instantiated—because the
2lifetimes of the instantiations are disjoint, it is possible for each instantation to simply use the same storage
3location. However, when an anonymous method captures a local variable, the effects of instantiation become
4apparent. [Example: The example
5using System;
6delegate void D();
7class Test
8{
9 |
static D[] F() { |
10 |
D[] result = new D[3]; |
11 |
for (int i = 0; i < 3; i++) { |
12 |
int x = i * 2 + 1; |
13 |
result[i] = delegate { Console.WriteLine(x); }; |
14 |
} |
15 |
return result; |
16 |
} |
17 |
static void Main() { |
18 |
foreach (D d in F()) d(); |
19}
20}
21produces the output:
221
233
245
25However, when the declaration of x is moved outside the loop:
26static D[] F() {
27 |
D[] result = new D[3]; |
28 |
int x; |
29 |
for (int i = 0; i < 3; i++) { |
30 |
x = i * 2 + 1; |
31 |
result[i] = delegate { Console.WriteLine(x); }; |
32 |
} |
33return result;
34}
35the output is:
365
375
385
39Note that the three delegates created in the version of F directly above will be equal according to the equality
40operator (§14.9.8). Furthermore, note that the compiler is permitted (but not required) to optimize the three
41instantiations into a single delegate instance (§14.5.14.4). end example]
42It is possible for anonymous method delegates to share some captured variables yet have separate instances
43of others. [Example: If F is changed to
44static D[] F() {
45 |
D[] result = new D[3]; |
46 |
int x = 0; |
47 |
for (int i = 0; i < 3; i++) { |
48 |
int y = 0; |
49 |
result[i] = delegate { Console.WriteLine("{0} {1}", ++x, ++y); }; |
50 |
} |
51return result;
52}
53the three delegates capture the same instance of x but separate instances of y, and the output is:
541 1
552 1
563 1
183