
- •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 |
1 |
static void Main() { |
2 |
object[] a = {1, "Hello", 123.456}; |
3 |
object o = a; |
4 |
F(a); |
5 |
F((object)a); |
6 |
F(o); |
7 |
F((object[])o); |
8}
9}
10produces the output
11System.Int32 System.String System.Double
12System.Object[]
13System.Object[]
14System.Int32 System.String System.Double
15In the first and last invocations of F, the normal form of F is applicable because an implicit conversion exists
16from the argument type to the parameter type (both are of type object[]). Thus, overload resolution selects
17the normal form of F, and the argument is passed as a regular value parameter. In the second and third
18invocations, the normal form of F is not applicable because no implicit conversion exists from the argument
19type to the parameter type (type object cannot be implicitly converted to type object[]). However, the
20expanded form of F is applicable, so it is selected by overload resolution. As a result, a one-element
21object[] is created by the invocation, and the single element of the array is initialized with the given
22argument value (which itself is a reference to an object[]). end example]
2317.5.2 Static and instance methods
24When a method declaration includes a static modifier, that method is said to be a static method. When no
25static modifier is present, the method is said to be an instance method.
26A static method does not operate on a specific instance, and it is a compile-time error to refer to this in a
27static method.
28An instance method operates on a given instance of a class, and that instance can be accessed as this
29(§14.5.7).
30The differences between static and instance members are discussed further in §17.2.5.
3117.5.3 Virtual methods
32When an instance method declaration includes a virtual modifier, that method is said to be a virtual
33method. When no virtual modifier is present, the method is said to be a non-virtual method.
34The implementation of a non-virtual method is invariant: The implementation is the same whether the
35method is invoked on an instance of the class in which it is declared or an instance of a derived class. In
36contrast, the implementation of a virtual method can be superseded by derived classes. The process of
37superseding the implementation of an inherited virtual method is known as overriding that method (§17.5.4).
38In a virtual method invocation, the run-time type of the instance for which that invocation takes place
39determines the actual method implementation to invoke. In a non-virtual method invocation, the compile-
40time type of the instance is the determining factor. In precise terms, when a method named N is invoked with
41an argument list A on an instance with a compile-time type C and a run-time type R (where R is either C or a
42class derived from C), the invocation is processed as follows:
43• First, overload resolution is applied to C, N, and A, to select a specific method M from the set of methods
44declared in and inherited by C. This is described in §14.5.5.1.
45• Then, if M is a non-virtual method, M is invoked.
46• Otherwise, M is a virtual method, and the most derived implementation of M with respect to R is invoked.
47For every virtual method declared in or inherited by a class, there exists a most derived implementation of
48the method with respect to that class. The most derived implementation of a virtual method M with respect to
49a class R is determined as follows:
284
Chapter 17 Classes
1• If R contains the introducing virtual declaration of M, then this is the most derived implementation
2of M.
3• Otherwise, if R contains an override of M, then this is the most derived implementation of M with
4respect to R.
5• Otherwise, the most derived implementation of M with respect to R is the same as the most derived
6implementation of M with respect to the direct base class of R.
7[Example: The following example illustrates the differences between virtual and non-virtual methods:
8using System;
9class A
10{
11 |
public void F() { Console.WriteLine("A.F"); } |
12public virtual void G() { Console.WriteLine("A.G"); }
13}
14class B: A
15{
16 |
new public void F() { Console.WriteLine("B.F"); } |
17public override void G() { Console.WriteLine("B.G"); }
18}
19class Test
20{
21 |
static void Main() { |
22 |
B b = new B(); |
23 |
A a = b; |
24 |
a.F(); |
25 |
b.F(); |
26 |
a.G(); |
27 |
b.G(); |
28}
29}
30In the example, A introduces a non-virtual method F and a virtual method G. The class B introduces a new
31non-virtual method F, thus hiding the inherited F, and also overrides the inherited method G. The example
32produces the output:
33A.F
34B.F
35B.G
36B.G
37Notice that the statement a.G() invokes B.G, not A.G. This is because the run-time type of the instance
38(which is B), not the compile-time type of the instance (which is A), determines the actual method
39implementation to invoke. end example]
40Because methods are allowed to hide inherited methods, it is possible for a class to contain several virtual
41methods with the same signature. This does not present an ambiguity problem, since all but the most derived
42method are hidden. [Example: In the following code
43using System;
44class A
45{
46public virtual void F() { Console.WriteLine("A.F"); }
47}
48class B: A
49{
50public override void F() { Console.WriteLine("B.F"); }
51}
52class C: B
53{
54new public virtual void F() { Console.WriteLine("C.F"); }
55}
285
C# LANGUAGE SPECIFICATION
1class D: C
2{
3public override void F() { Console.WriteLine("D.F"); }
4}
5class Test
6{
7 |
static void Main() { |
8 |
D d = new D(); |
9 |
A a = d; |
10 |
B b = d; |
11 |
C c = d; |
12 |
a.F(); |
13 |
b.F(); |
14 |
c.F(); |
15 |
d.F(); |
16}
17}
18the C and D classes contain two virtual methods with the same signature: The one introduced by A and the
19one introduced by C. The method introduced by C hides the method inherited from A. Thus, the override
20declaration in D overrides the method introduced by C, and it is not possible for D to override the method
21introduced by A. The example produces the output:
22B.F
23B.F
24D.F
25D.F
26Note that it is possible to invoke the hidden virtual method by accessing an instance of D through a less
27derived type in which the method is not hidden. end example]
2817.5.4 Override methods
29When an instance method declaration includes an override modifier, the method is said to be an override
30method. An override method overrides an inherited virtual method with the same signature. Whereas a
31virtual method declaration introduces a new method, an override method declaration specializes an existing
32inherited virtual method by providing a new implementation of that method.
33The method overridden by an override declaration is known as the overridden base method. For an
34override method M declared in a class C, the overridden base method is determined by examining each base
35class of C, starting with the direct base class of C and continuing with each successive direct base class, until
36an accessible method with the same signature as M is located. For the purposes of locating the overridden
37base method, a method is considered accessible if it is public, if it is protected, if it is protected
38internal, or if it is internal and declared in the same program as C.
39A compile-time error occurs unless all of the following are true for an override declaration:
40• An overridden base method can be located as described above.
41• The overridden base method is a virtual, abstract, or override method. In other words, the overridden
42base method cannot be static or non-virtual.
43• The overridden base method is not a sealed method.
44• The override declaration and the overridden base method have the same return type.
45• The override declaration and the overridden base method have the same declared accessibility. In other
46words, an override declaration cannot change the accessibility of the virtual method.
47An override declaration can access the overridden base method using a base-access (§14.5.8). [Example: In
48the following code
49class A
50{
51 |
int x; |
286
|
Chapter 17 Classes |
1 |
public virtual void PrintFields() { |
2 |
Console.WriteLine("x = {0}", x); |
3}
4}
5class B: A
6{
7 |
int y; |
8 |
public override void PrintFields() { |
9 |
base.PrintFields(); |
10 |
Console.WriteLine("y = {0}", y); |
11}
12}
13the base.PrintFields() invocation in B invokes the PrintFields method declared in A. A base-
14access disables the virtual invocation mechanism and simply treats the base method as a non-virtual method.
15Had the invocation in B been written ((A)this).PrintFields(), it would recursively invoke the
16PrintFields method declared in B, not the one declared in A, since PrintFields is virtual and the run-time
17type of ((A)this) is B. end example]
18Only by including an override modifier can a method override another method. In all other cases, a
19method with the same signature as an inherited method simply hides the inherited method. [Example: In the
20following code
21class A
22{
23public virtual void F() {}
24}
25class B: A
26{
27 |
public virtual void F() {} |
// Warning, hiding inherited F() |
28}
29the F method in B does not include an override modifier and therefore does not override the F method
30in A. Rather, the F method in B hides the method in A, and a warning is reported because the declaration does
31not include a new modifier. end example]
32[Example: In the following code
33class A
34{
35public virtual void F() {}
36}
37class B: A
38{
39 |
new private void F() {} |
// Hides A.F within B |
40}
41class C: B
42{
43 |
public override void F() {} // Ok, overrides A.F |
44}
45the F method in B hides the virtual F method inherited from A. Since the new F in B has private access, its
46scope only includes the class body of B and does not extend to C. Therefore, the declaration of F in C is
47permitted to override the F inherited from A. end example]
4817.5.5 Sealed methods
49When an instance method declaration includes a sealed modifier, that method is said to be a sealed
50method. A sealed method overrides an inherited virtual method with the same signature. A sealed method
51shall also be marked with the override modifier. Use of the sealed modifier prevents a derived class
52from further overriding the method.
53[Example: The example
54using System;
287