- •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
1class Text
2{
3 |
public Text(): this(0, 0, null) {} |
4 |
public Text(int x, int y): this(x, y, null) {} |
5 |
public Text(int x, int y, string s) { |
6 |
// Actual constructor implementation |
7}
8}
9the first two instance constructors merely provide the default values for the missing arguments. Both use a
10this(…) constructor initializer to invoke the third instance constructor, which actually does the work of
11initializing the new instance. The effect is that of optional constructor parameters:
12 |
Text |
t1 |
= |
new |
Text(); |
// |
Same |
as |
Text(0, |
0, null) |
13 |
Text |
t2 |
= |
new |
Text(5, 10); |
// |
Same |
as |
Text(5, |
10, null) |
14Text t3 = new Text(5, 20, "Hello");
15end note]
1617.11 Static constructors
17A static constructor is a member that implements the actions required to initialize a class. Static
18constructors are declared using static-constructor-declarations:
19static-constructor-declaration:
20 |
attributesopt static-constructor-modifiers identifier ( ) static-constructor-body |
21 |
static-constructor-modifiers: |
22 |
externopt static |
23static externopt
24static-constructor-body:
25 |
block |
26;
27A static-constructor-declaration can include a set of attributes (§24) and an extern modifier (§17.5.7).
28The identifier of a static-constructor-declaration shall name the class in which the static constructor is
29declared. If any other name is specified, a compile-time error occurs.
30When a static constructor declaration includes an extern modifier, the static constructor is said to be an
31external static constructor. Because an external static constructor declaration provides no actual
32implementation, its static-constructor-body consists of a semicolon. For all other static constructor
33declarations, the static-constructor-body consists of a block, which specifies the statements to execute in
34order to initialize the class. This corresponds exactly to the method-body of a static method with a void
35return type (§17.5.8).
36Static constructors are not inherited, and cannot be called directly.
37The static constructor for a non-generic class executes at most once in a given application domain. The static
38constructor for a generic class declaration executes at most once for each closed constructed type
39constructed from the class declaration (§26.1.5). The execution of a static constructor is triggered by the first
40of the following events to occur within an application domain:
41• An instance of the class is created.
42• Any of the static members of the class are referenced.
43If a class contains the Main method (§10.1) in which execution begins, the static constructor for that class
44executes before the Main method is called. If a class contains any static fields with initializers, those
45initializers are executed in textual order immediately prior to executing the static constructor (§17.4.5).
46[Example: The example
47using System;
316
Chapter 17 Classes
1class Test
2{
3 |
static void Main() { |
4 |
A.F(); |
5 |
B.F(); |
6}
7}
8class A
9{
10 |
static A() { |
11 |
Console.WriteLine("Init A"); |
12 |
} |
13 |
public static void F() { |
14 |
Console.WriteLine("A.F"); |
15}
16}
17class B
18{
19 |
static B() { |
20 |
Console.WriteLine("Init B"); |
21 |
} |
22 |
public static void F() { |
23 |
Console.WriteLine("B.F"); |
24}
25}
26shall produce the output:
27Init A
28A.F
29Init B
30B.F
31because the execution of A's static constructor is triggered by the call to A.F, and the execution of B's static
32constructor is triggered by the call to B.F. end example]
33It is possible to construct circular dependencies that allow static fields with variable initializers to be
34observed in their default value state.
35[Example: The example
36using System;
37class A
38{
39 |
public static int X; |
40static A() { X = B.Y + 1;}
41}
42class B
43{
44 |
public static int Y = A.X + 1; |
45 |
static B() {} |
46 |
static void Main() { |
47 |
Console.WriteLine("X = {0}, Y = {1}", A.X, B.Y); |
48}
49}
50produces the output
51X = 1, Y = 2
52To execute the Main method, the system first runs the initializer for B.Y, prior to class B's static constructor.
53Y's initializer causes A's static constructor to be run because the value of A.X is referenced. The static
54constructor of A in turn proceeds to compute the value of X, and in doing so fetches the default value of Y,
55which is zero. A.X is thus initialized to 1. The process of running A's static field initializers and static
56constructor then completes, returning to the calculation of the initial value of Y, the result of which
57becomes 2. end example]
317
C# LANGUAGE SPECIFICATION
117.12 Destructors
2A destructor is a member that implements the actions required to destruct an instance of a class. A
3destructor is declared using a destructor-declaration:
4destructor-declaration:
5 |
attributesopt externopt ~ identifier ( ) destructor-body |
6 |
destructor-body: |
7 |
block |
8;
9A destructor-declaration can include a set of attributes (§24).
10The identifier of a destructor-declarator shall name the class in which the destructor is declared. If any other
11name is specified, a compile-time error occurs.
12When a destructor declaration includes an extern modifier, the destructor is said to be an external
13destructor. Because an external destructor declaration provides no actual implementation, its destructor-
14body consists of a semicolon. For all other destructors, the destructor-body consists of a block, which
15specifies the statements to execute in order to destruct an instance of the class. A destructor-body
16corresponds exactly to the method-body of an instance method with a void return type (§17.5.8).
17Destructors are not inherited. Thus, a class has no destructors other than the one which can be declared in
18that class.
19[Note: Since a destructor is required to have no parameters, it cannot be overloaded, so a class can have, at
20most, one destructor. end note]
21Destructors are invoked automatically, and cannot be invoked explicitly. An instance becomes eligible for
22destruction when it is no longer possible for any code to use that instance. Execution of the destructor for the
23instance can occur at any time after the instance becomes eligible for destruction. When an instance is
24destructed, the destructors in that instance’s inheritance chain are called, in order, from most derived to least
25derived [Example: The output of the example
26using System;
27class A
28{
29 |
~A() { |
30 |
Console.WriteLine("A's destructor"); |
31}
32}
33class B: A
34{
35 |
~B() { |
36 |
Console.WriteLine("B's destructor"); |
37}
38}
39class Test
40{
41 |
static void Main() { |
42 |
B b = new B(); |
43 |
b = null; |
44 |
GC.Collect(); |
45 |
GC.WaitForPendingFinalizers(); |
46}
47}
48is
49B’s destructor
50A’s destructor
51since destructors in an inheritance chain are called in order, from most derived to least derived. The
52GC.Collect method is not required, but can be provided by an implementation. end example]
318
Chapter 17 Classes
1Destructors can be implemented by overriding the virtual method Finalize on System.Object. In any
2event, C# programs are not permitted to override this method or call it (or overrides of it) directly.
3[Example: For instance, the program
4class A
5{
6 |
protected override void Finalize() {} // error |
|
7 |
public void F() { |
|
8 |
this.Finalize(); |
// error |
9}
10}
11contains two errors. end example]
12The compiler behaves as if System.Object.Finalize, and overrides of it, does not exist at all.
13[Example: Thus, this program:
14class A
15{
16 |
void Finalize() {} |
// permitted |
17}
18is valid and the method shown hides System.Object's Finalize method, without requiring the new
19modifier. end example]
20For a discussion of the behavior when an exception is thrown from a destructor, see §23.3.
319
