- •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 10 Basic concepts
1 |
namespace X |
// X |
2 |
{ |
|
3 |
class B |
// X.B |
4 |
{ |
|
5 |
class C {} |
// X.B.C |
6 |
} |
|
7 |
namespace Y |
// X.Y |
8 |
{ |
|
9 |
class D {} |
// X.Y.D |
10}
11}
12 |
namespace X.Y |
// X.Y |
13 |
{ |
|
14 |
class E {} |
// X.Y.E |
15 |
class G<T> { |
// X.Y.G<> |
16 |
class H {} |
// X.Y.G<>.H |
17 |
} |
|
18 |
class G<S,T> { |
// X.Y.G<,> |
19 |
class H<U> {} |
// X.Y.G<,>.H<> |
20}
21}
22end example]
2310.9 Automatic memory management
24C# employs automatic memory management, which frees developers from manually allocating and freeing
25the memory occupied by objects. Automatic memory management policies are implemented by a garbage
26collector. The memory management life cycle of an object is as follows:
271. When the object is created, memory is allocated for it, the constructor is run, and the object is
28considered live.
292. If no part of the object can be accessed by any possible continuation of execution, other than the running
30of destructors, the object is considered no longer in use, and it becomes eligible for destruction. [Note:
31Implementations might choose to analyze code to determine which references to an object can be used in
32the future. For instance, if a local variable that is in scope is the only existing reference to an object, but
33that local variable is never referred to in any possible continuation of execution from the current
34execution point in the procedure, an implementation might (but is not required to) treat the object as no
35longer in use. end note]
363. Once the object is eligible for destruction, at some unspecified later time the destructor (§17.12) (if any)
37for the object is run. Unless overridden by explicit calls, the destructor for the object is run once only.
384. Once the destructor for an object is run, if that object, or any part of it, cannot be accessed by any
39possible continuation of execution, including the running of destructors, the object is considered
40inaccessible and the object becomes eligible for collection.
415. Finally, at some time after the object becomes eligible for collection, the garbage collector frees the
42memory associated with that object.
43The garbage collector maintains information about object usage, and uses this information to make memory
44management decisions, such as where in memory to locate a newly created object, when to relocate an
45object, and when an object is no longer in use or inaccessible.
46Like other languages that assume the existence of a garbage collector, C# is designed so that the garbage
47collector can implement a wide range of memory management policies. For instance, C# does not require
48that destructors be run or that objects be collected as soon as they are eligible, or that destructors be run in
49any particular order, or on any particular thread.
50The behavior of the garbage collector can be controlled, to some degree, via static methods on the class
51System.GC. [Note: While not required by this specification, a Collect method might be provided on the
101
C# LANGUAGE SPECIFICATION
1GC class which requests that a collection be performed. The following examples presume the existence of
2such a method. end note]
3[Example: Since the garbage collector is allowed wide latitude in deciding when to collect objects and run
4destructors, a conforming implementation might produce output that differs from that shown by the
5following code. The program
6using System;
7class A
8{
9 |
~A() { |
10 |
Console.WriteLine("Destruct instance of A"); |
11}
12}
13class B
14{
15 |
object |
Ref; |
16 |
public |
B(object o) { |
17 |
Ref = o; |
|
18 |
} |
|
19 |
~B() { |
|
20 |
Console.WriteLine("Destruct instance of B"); |
21}
22}
23class Test
24{
25 |
static void Main() { |
26 |
B b = new B(new A()); |
27 |
b = null; |
28 |
GC.Collect(); |
29 |
GC.WaitForPendingFinalizers(); |
30}
31}
32creates an instance of class A and an instance of class B. These objects become eligible for garbage
33collection when the variable b is assigned the value null, since after this time it is impossible for any user-
34written code to access them. The output could be either
35Destruct instance of A
36Destruct instance of B
37or
38Destruct instance of B
39Destruct instance of A
40because the language imposes no constraints on the order in which objects are garbage collected.
41In subtle cases, the distinction between “eligible for destruction” and “eligible for collection” can be
42important. For example,
43using System;
44class A
45{
46 |
~A() { |
47 |
Console.WriteLine("Destruct instance of A"); |
48 |
} |
49 |
public void F() { |
50 |
Console.WriteLine("A.F"); |
51 |
Test.RefA = this; |
52}
53}
102
Chapter 10 Basic concepts
1class B
2{
3 |
public A Ref; |
4 |
~B() { |
5 |
Console.WriteLine("Destruct instance of B"); |
6 |
Ref.F(); |
7}
8}
9class Test
10{
11 |
public static A RefA; |
12 |
public static B RefB; |
13 |
static void Main() { |
14 |
RefB = new B(); |
15 |
RefA = new A(); |
16 |
RefB.Ref = RefA; |
17 |
RefB = null; |
18 |
RefA = null; |
19 |
// A and B now eligible for destruction |
20 |
GC.Collect(); |
21 |
GC.WaitForPendingFinalizers(); |
22 |
// B now eligible for collection, but A is not |
23 |
if (RefA != null) |
24 |
Console.WriteLine("RefA is not null"); |
25}
26}
27In the above program, if the garbage collector chooses to run the destructor of A before the destructor of B,
28then the output of this program might be:
29Destruct instance of A
30Destruct instance of B
31A.F
32RefA is not null
33Note that although the instance of A was not in use and A's destructor was run, it is still possible for methods
34of A (in this case, F) to be called from another destructor. Also, note that running of a destructor might cause
35an object to become usable from the mainline program again. In this case, the running of B's destructor
36caused an instance of A that was previously not in use to become accessible from the live reference RefA.
37After the call to WaitForPendingFinalizers, the instance of B is eligible for collection, but the instance
38of A is not, because of the reference RefA.
39To avoid confusion and unexpected behavior, it is generally a good idea for destructors to only perform
40cleanup on data stored in their object's own fields, and not to perform any actions on referenced objects or
41static fields. end example]
4210.10 Execution order
43Execution shall proceed such that the side effects of each executing thread are preserved at critical execution
44points. A side effect is defined as a read or write of a volatile field, a write to a non-volatile variable, a write
45to an external resource, and the throwing of an exception. The critical execution points at which the order of
46these side effects shall be preserved are references to volatile fields (§17.4.3), lock statements (§15.12), and
47thread creation and termination. An implementation is free to change the order of execution of a
48C# program, subject to the following constraints:
49• Data dependence is preserved within a thread of execution. That is, the value of each variable is
50computed as if all statements in the thread were executed in original program order.
51• Initialization ordering rules are preserved (§17.4.4 and §17.4.5).
52• The ordering of side effects is preserved with respect to volatile reads and writes (§17.4.3). Additionally,
53an implementation need not evaluate part of an expression if it can deduce that that expression’s value is
54not used and that no needed side effects are produced (including any caused by calling a method or
55accessing a volatile field). When program execution is interrupted by an asynchronous event (such as an
103
C# LANGUAGE SPECIFICATION
1exception thrown by another thread), it is not guaranteed that the observable side effects are visible in
2the original program order.
104