- •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 26 Generics
126. Generics
226.1 Generic class declarations
3A generic class declaration is a declaration of a class that requires type arguments to be supplied in order to
4form actual types.
5[Note: A class declaration (§17.1), can optionally define type parameters and their associated constraints:
6class-declaration:
7 |
attributesopt class-modifiersopt partialopt class identifier type-parameter-listopt |
8 |
class-baseopt type-parameter-constraints-clausesopt class-body ;opt |
9A class declaration shall not supply type-parameter-constraints-clauses (§26.7) unless it also supplies a
10type-parameter-list (§26.1.1).
11A class declaration that supplies a type-parameter-list is a generic class declaration. end note]
12Any class nested inside a generic class declaration or a generic struct declaration (§26.2) is itself a generic
13class declaration, since type parameters for the containing type shall be supplied to create a constructed type.
14Generic class declarations follow the same rules as non-generic class declarations except where noted.
15Generic class declarations can be nested inside non-generic class declarations.
16A generic class is referenced using a constructed type (§26.5). [Example: Given the generic class declaration
17class List<T> {}
18some examples of constructed types are List<T>, List<int> and List<List<string>>. end example]
19A constructed type that uses one or more type parameters, such as List<T>, is called an open constructed
20type (§26.5). A constructed type that uses no type parameters, such as List<int>, is called a closed
21constructed type (§26.5).
22Generic types can be “overloaded” on the number of type parameters; that is two type declarations within
23the same namespace or outer type declaration can use the same identifier as long as they have a different
24number of type parameters.
25class C {}
26 |
class C<V> {} |
// OK |
27 |
struct C<U,V> {} |
// OK |
28 |
class C<A,B> {} |
// Error, C with two type parameters defined twice |
29The type lookup rules used during type name resolution (§10.8), simple name resolution (§14.5.2) and
30member access (§14.5.4) respect the number of type parameters.
31The base interfaces of a generic class declaration shall satisfy the uniqueness rule described in §26.3.1.
3226.1.1 Type parameters
33Type parameters can be supplied in a class declaration. Each type parameter is a simple identifier that
34denotes a placeholder for a type argument supplied to create a constructed type. A type parameter is a formal
35placeholder for a type that will be supplied later. By constrast, a type argument (§26.5.1) is the actual type
36that is substituted for the type parameter when a constructed type is created.
37type-parameter-list:
38< type-parameters >
39type-parameters:
40 |
attributesopt type-parameter |
41 |
type-parameters , attributesopt type-parameter |
397
C# LANGUAGE SPECIFICATION
1
2
type-parameter: identifier
3Each type parameter in a class declaration defines a name in the declaration space (§10.3) of that class.
4Thus, it cannot have the same name as another type parameter or a member declared in that class. A type
5parameter shall not have the same name as the type itself.
6The scope (§10.7) of a type parameter on a class includes the class-base, type-parameter-constraints-
7clauses, and class-body. Unlike members of a class, this scope does not extend to derived classes. Within its
8scope, a type parameter can be used as a type.
9Since a type parameter can be instantiated with many different actual type arguments, type parameters have
10slightly different operations and restrictions than other types. [Note: These include:
11• A type parameter cannot be used directly to declare a base class or interface (§17.1.2).
12• The rules for member lookup on type parameters depend on the constraints, if any, applied to the type
13parameter. They are detailed in §26.7.2.
14• The available conversions for a type parameter depend on the constraints, if any, applied to the type
15parameter. They are detailed in §26.7.4.
16• The literal null cannot be converted to a type given by a type parameter, except if the type parameter is
17known to be a reference type (§26.7.4). However, a default value expression (§14.5.13) can be used
18instead. In addition, a value with a type given by a type parameter can be compared with null using ==
19and != (§14.9.6) unless the type parameter has the value type constraint (§26.7.4).
20• A new expression (§14.5.10.1) can only be used with a type parameter if the type parameter is
21constrained by a constructor-constraint or the value type constraint (§26.7).
22• A type parameter cannot be used anywhere within an attribute (§24.2).
23• A type parameter cannot be used in a member access or type name to identify a static member or a
24nested type (§10.8, §14.5.4).
25• In unsafe code, a type parameter cannot be used as an unmanaged-type (§25.2).
26end note]
27As a type, type parameters are purely a compile-time construct. At run-time, each type parameter is bound to
28a run-time type that was specified by supplying a type argument to the generic type declaration. Thus, the
29type of a variable declared with a type parameter will, at run-time, be a closed constructed type (§26.5.2).
30The run-time execution of all statements and expressions involving type parameters uses the actual type that
31was supplied as the type argument for that parameter.
3226.1.2 The instance type
33Each class declaration has an associated constructed type, the instance type. For a generic class declaration,
34the instance type is formed by creating a constructed type (§26.5) from the type declaration, with each of the
35supplied type arguments being the corresponding type parameter. Since the instance type uses the type
36parameters, it can only be used where the type parameters are in scope; that is, inside the class declaration.
37The instance type is the type of this for code written inside the class declaration. For non-generic classes,
38the instance type is simply the declared class. [Example: The following shows several class declarations
39along with their instance types:
40 |
class A<T> |
// instance type: A<T> |
41 |
{ |
|
42 |
class B {} |
// instance type: A<T>.B |
43 |
class C<U> {} |
// instance type: A<T>.C<U> |
44 |
} |
|
45 |
class D {} |
// instance type: D |
46 |
end example] |
|
398
Chapter 26 Generics
126.1.3 Members of generic classes
2All members of a generic class can use type parameters from any enclosing class, either directly or as part of
3a constructed type. When a particular closed constructed type (§26.5.2) is used at run-time, each use of a
4type parameter is replaced with the actual type argument supplied to the constructed type. [Example:
5class C<V>
6{
7 |
public V F1; |
8 |
public C<V> F2 = null; |
9 |
public C(V x) { |
10 |
this.F1 = x; |
11 |
this.F2 = this; |
12}
13}
14class Application
15{
16 |
static void Main() { |
|
|
17 |
C<int> x1 |
= new C<int>(1); |
|
18 |
Console.WriteLine(x1.F1); |
// Prints 1 |
|
19 |
C<double> |
x2 = new C<double>(3.1415); |
|
20 |
Console.WriteLine(x2.F1); |
// Prints 3.1415 |
|
21}
22}
23end example]
24Within instance function members, the type of this is the instance type (§26.1.2) of the containing
25declaration.
26Apart from the use of type parameters as types, members in generic class declarations follow the same rules
27as members of non-generic classes. Additional rules that apply to particular kinds of members are discussed
28in the following subclauses.
2926.1.4 Static fields in generic classes
30A static variable in a generic class declaration is shared amongst all instances of the same closed constructed
31type (§26.5.2), but is not shared amongst instances of different closed constructed types. These rules apply
32regardless of whether the type of the static variable involves any type parameters or not.
33[Example:
34class C<V>
35{
36 |
static |
int count = 0; |
37 |
public C() { |
|
38 |
count++; |
|
39 |
} |
|
40 |
public static int Count { |
|
41 |
get { return count; } |
|
42}
43}
44
45class Application
46{
47 |
static void Main() { |
|
48 |
C<int> x1 = new C<int>(); |
|
49 |
Console.WriteLine(C<int>.Count); |
// Prints 1 |
50 |
C<double> x2 = new C<double>(); |
|
51 |
Console.WriteLine(C<double>.Count); // Prints 1 |
|
52 |
Console.WriteLine(C<int>.Count); |
// Prints 1 |
399
|
C# LANGUAGE SPECIFICATION |
|
1 |
C<int> x3 = new C<int>(); |
|
2 |
Console.WriteLine(C<int>.Count); |
// Prints 2 |
3}
4}
5end example]
626.1.5 Static constructors in generic classes
7A static constructor in a generic class is used to initialize static fields and to perform other initialization for
8each different closed constructed type that is created from that generic class declaration. The type parameters
9of the generic type declaration are in scope, and can be used, within the body of the static constructor.
10A new closed constructed class type is initialized the first time that either:
11• An instance of the closed constructed type is created.
12• Any of the static members of the closed constructed type are referenced.
13To initialize a new closed constructed class type, first a new set of static fields (§26.1.4) for that particular
14closed constructed type is created. Each of the static fields is initialized to its default value (§12.2). Next, the
15static field initializers (§17.4.5.1) are executed for those static fields. Finally, the static constructor is
16executed.
17Because the static constructor is executed exactly once for each closed constructed class type, it is a
18convenient place to enforce run-time checks on the type parameter that cannot be checked at compile-time
19via constraints (§26.7). [Example: The following type uses a static constructor to enforce that the type
20argument is an enum:
21class Gen<T> where T: struct
22{
23 |
static Gen() { |
24 |
if (!typeof(T).IsEnum) { |
25 |
throw new ArgumentException("T must be an enum"); |
26 |
} |
27}
28}
29end example]
3026.1.6 Accessing protected members
31[Note: The accessibility domain (§10.5.2) of a protected member declared in a generic class includes the
32program text of all class declarations derived from any type constructed from that generic class. In the
33example:
34class C<T>
35{
36protected static T x;
37}
38class D: C<string>
39{
40 |
static void |
Main() { |
41 |
C<int>.x |
= 5; |
42}
43}
44The reference to protected member C<int>.x in D is valid even though the class D derives from
45C<string>.
46end note]
47Within a generic class declaration, access to inherited protected instance members (§10.5.3) is permitted
48through an instance of any class type constructed from the generic class. [Example: In the following code
400
