
- •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
C# LANGUAGE SPECIFICATION
115.10 The try statement
2The try statement provides a mechanism for catching exceptions that occur during execution of a block.
3Furthermore, the try statement provides the ability to specify a block of code that is always executed when
4control leaves the try statement.
5try-statement:
6 |
try block catch-clauses |
7 |
try block catch-clausesopt finally-clause |
8 |
catch-clauses: |
9 |
specific-catch-clauses |
10 |
specific-catch-clausesopt general-catch-clause |
11 |
specific-catch-clauses: |
12 |
specific-catch-clause |
13 |
specific-catch-clauses specific-catch-clause |
14 |
specific-catch-clause: |
15 |
catch ( class-type identifieropt ) block |
16 general-catch-clause:
17catch block
18finally-clause:
19finally block
20There are three possible forms of try statements:
21• A try block followed by one or more catch blocks.
22• A try block followed by a finally block.
23• A try block followed by one or more catch blocks followed by a finally block.
24When a catch clause specifies a class-type, the type shall be System.Exception or a type that derives
25from System.Exception.
26When a catch clause specifies both a class-type and an identifier, an exception variable of the given name
27and type is declared. The exception variable corresponds to a local variable with a scope that extends over
28the catch block. During execution of the catch block, the exception variable represents the exception
29currently being handled. For purposes of definite assignment checking, the exception variable is considered
30definitely assigned in its entire scope.
31Unless a catch clause includes an exception variable name, it is impossible to access the exception object
32in the catch block.
33The type named in a catch clause can be a type parameter only if that type parameter (§26.1.1) has
34System.Exception (or a subclass thereof) as its effective base class (§26.7).
35A catch clause that specifies neither an exception type nor an exception variable name is called a general
36catch clause. A try statement can only have one general catch clause, and if one is present it shall be the
37last catch clause.
38[Note: Some environments, especially those supporting multiple languages, might support exceptions that
39are not representable as an object derived from System.Exception, although such an exception could
40never be generated by C# code. In such an environment, a general catch clause might be used to catch such
41an exception. Thus, a general catch clause is semantically different from one that specifies the type
42System.Exception, in that the former might also catch exceptions from other languages. end note]
43In order to locate a handler for an exception, catch clauses are examined in lexical order. A compile-time
44error occurs if a catch clause specifies a type that is the same as, or is derived from, a type that was
45specified in an earlier catch clause for the same try. [Note: Without this restriction, it would be possible to
46write unreachable catch clauses. end note]
234
Chapter 15 Statements
1Within a catch block, a throw statement (§15.9.5) with no expression can be used to re-throw the
2exception that was caught by the catch block. Assignments to an exception variable do not alter the
3exception that is re-thrown.
4[Example: In the following code
5using System;
6class Test
7{
8 |
static void F() { |
|
9 |
try { |
|
10 |
G(); |
|
11 |
} |
|
12 |
catch (Exception e) { |
|
13 |
Console.WriteLine("Exception in F: " + e.Message); |
|
14 |
e = new Exception("F"); |
|
15 |
throw; |
// re-throw |
16 |
} |
|
17 |
} |
|
18 |
static void G() { |
|
19 |
throw new Exception("G"); |
|
20 |
} |
|
21 |
static void Main() { |
|
22 |
try { |
|
23 |
F(); |
|
24 |
} |
|
25 |
catch (Exception e) { |
|
26 |
Console.WriteLine("Exception in Main: " + e.Message); |
|
27 |
} |
|
28}
29}
30the method F catches an exception, writes some diagnostic information to the console, alters the exception
31variable, and re-throws the exception. The exception that is re-thrown is the original exception, so the output
32produced is:
33Exception in F: G
34Exception in Main: G
35If the first catch block had thrown e instead of rethrowing the current exception, the output produced would
36be as follows:
37Exception in F: G
38Exception in Main: F
39end example]
40It is a compile-time error for a break, continue, or goto statement to transfer control out of a finally
41block. When a break, continue, or goto statement occurs in a finally block, the target of the statement
42shall be within the same finally block, or otherwise a compile-time error occurs.
43It is a compile-time error for a return statement to occur in a finally block.
44A try statement is executed as follows:
45• Control is transferred to the try block.
46• When and if control reaches the end point of the try block:
47o If the try statement has a finally block, the finally block is executed.
48o Control is transferred to the end point of the try statement.
49• If an exception is propagated to the try statement during execution of the try block:
50o The catch clauses, if any, are examined in order of appearance to locate a suitable handler for the
51exception. The first catch clause that specifies the exception type or a base type of the exception
235
C# LANGUAGE SPECIFICATION
1type is considered a match. A general catch clause is considered a match for any exception type. If
2a matching catch clause is located:
3• If the matching catch clause declares an exception variable, the exception object is assigned to
4 |
the exception variable. |
5• Control is transferred to the matching catch block.
6• When and if control reaches the end point of the catch block:
7 |
o If the try statement has a finally block, the finally block is executed. |
8o Control is transferred to the end point of the try statement.
9• If an exception is propagated to the try statement during execution of the catch block:
10 |
o If the try statement has a finally block, the finally block is executed. |
11o The exception is propagated to the next enclosing try statement.
12o If the try statement has no catch clauses or if no catch clause matches the exception:
13• If the try statement has a finally block, the finally block is executed.
14• The exception is propagated to the next enclosing try statement.
15The statements of a finally block are always executed when control leaves a try statement. This is true
16whether the control transfer occurs as a result of normal execution, as a result of executing a break,
17continue, goto, or return statement, or as a result of propagating an exception out of the try statement.
18If an exception is thrown during execution of a finally block, the exception is propagated to the next
19enclosing try statement. If another exception was in the process of being propagated, that exception is lost.
20The process of propagating an exception is discussed further in the description of the throw statement
21(§15.9.5).
22The try block of a try statement is reachable if the try statement is reachable.
23A catch block of a try statement is reachable if the try statement is reachable.
24The finally block of a try statement is reachable if the try statement is reachable.
25The end point of a try statement is reachable if both of the following are true:
26• The end point of the try block is reachable or the end point of at least one catch block is reachable.
27• If a finally block is present, the end point of the finally block is reachable.
2815.11 The checked and unchecked statements
29The checked and unchecked statements are used to control the overflow checking context for integral-
30type arithmetic operations and conversions.
31checked-statement:
32checked block
33unchecked-statement:
34unchecked block
35The checked statement causes all expressions in the block to be evaluated in a checked context, and the
36unchecked statement causes all expressions in the block to be evaluated in an unchecked context.
37The checked and unchecked statements are precisely equivalent to the checked and unchecked
38operators (§14.5.12), except that they operate on blocks instead of expressions.
236
Chapter 15 Statements
115.12 The lock statement
2The lock statement obtains the mutual-exclusion lock for a given object, executes a statement, and then
3releases the lock.
4lock-statement:
5 |
lock ( expression ) embedded-statement |
6The compile time type of the expression of a lock statement shall be a reference-type or a type parameter
7(§26.1.1). It is a compile-time error for the compile time type of the expression to denote a value-type. When
8the compile time type of expression is a type parameter (§26.1.1) and the run-time type of the expression is a
9value type, the value of the expression is boxed and the mutual exclusion lock is obtained on the boxed
10value. In this case the locking will have no effect since the boxed value could not have any other references
11to it.
12A lock statement of the form
13lock (x) …
14is precisely equivalent to:
15object obj = x;
16System.Threading.Monitor.Enter(obj);
17try {
18…
19}
20finally {
21System.Threading.Monitor.Exit(obj);
22}
23[Example:
24class Cache
25{
26 |
public void Add(object x) { |
27 |
lock (key) { |
28 |
… |
29 |
} |
30 |
} |
31 |
public void Remove(object x) { |
32 |
lock (key) { |
33 |
… |
34 |
} |
35 |
} |
36private readonly object key = new object();
37}
38end example]
3915.13 The using statement
40The using statement obtains one or more resources, executes a statement, and then disposes of the resource.
41using-statement:
42 |
using ( resource-acquisition ) embedded-statement |
43 |
resource-acquisition: |
44 |
local-variable-declaration |
45 |
expression |
46A resource is a class or struct that either has a suitable Dispose method or implements the
47System.IDisposable interface. The System.IDisposable interface includes a single parameterless
48method named Dispose. Code that is using a resource can call Dispose to indicate that the resource is no
49longer needed. If Dispose is not called, then automatic disposal eventually occurs as a consequence of
50garbage collection (assuming the destructor of the resource type calls Dispose or otherwise performs the
51equivalent actions).
237
C# LANGUAGE SPECIFICATION
1Local variables declared in a resource-acquisition are read-only, and shall include an initializer. A compile-
2time error occurs if the embedded statement attempts to modify these local variables (via assignment or the
3++ and -- operators) or pass them as ref or out parameters.
4A using statement is translated into three parts: acquisition, usage, and disposal. Usage of the resource is
5implicitly enclosed in a try statement that includes a finally clause. This finally clause disposes of the
6resource. If a null resource is acquired, then no call to Dispose is made, and no exception is thrown.
7A using statement of the form
8using (expression) embedded-statement
9is equivalent to a using statement of the form:
10using (ResourceType resource = expression) embedded-statement
11where ResourceType is the type of the expression and the resource variable is not visible to or
12accessible from any source code of the program.
13A using statement of the form
14using (ResourceType resource = expression) embedded-statement
15corresponds to the expansion:
16{
17 |
ResourceType resource = expression; |
18 |
try { |
19 |
embedded-statement |
20 |
} |
21 |
finally { |
22 |
… // Dispose of resource |
23}
24}
25The resource variable is read-only in the embedded statement.
26The precise form of the finally block is determined as follows:
27• First determine whether the resource type R has an appropriate Dispose method:
28o Perform member lookup on the type R with identifier Dispose and no type arguments. If the
29member lookup does not produce a match or produces an ambiguity or produces a match that is not
30a method group, check for the System.IDisposable interface as described below. It is
31recommended that a warning be issued if member lookup produces anything except a method group
32or no match.
33o Perform overload resolution using the resulting method group and an empty argument list. If
34overload resolution results in no applicable methods or results in an ambiguity or results in a single
35best method but that method is either static or not public or has a return type other than void, check
36for the System.IDisposable interface as described below. It is recommended that a warning be
37issued if overload resolution produces anything except an unambiguous public instance method with
38void return type or no applicable methods.
39o If ResourceType is a value type or a type parameter with the value type constraint (§26.7), the
40finally clause is expanded to:
41finally {
42resource.Dispose();
43}
44o Otherwise, the finally clause is expanded to:
45finally {
46if (resource != null) resource.Dispose();
47}
48• Otherwise, check for the System.IDisposable interface:
238