- •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
1• For each type parameter, all of the inferences for that type parameter infer the same type argument (in
2short, the set of inferences is consistent).
3If the generic method was declared with a parameter array (§17.5.1.4), then type inference is first performed
4against the method in its normal form. If type inference succeeds, and the resultant method is applicable,
5then the method is eligible for overload resolution in its normal form. Otherwise, type inference is
6performed against the method in its expanded form (§14.4.2.1).
726.6.5 Using a generic method with a delegate
8An instance of a delegate can be created that refers to a generic method declaration. The exact compile-time
9processing of a delegate creation expression, including a delegate creation expression that refers to a generic
10method, is described in §14.5.10.3.
11The type arguments used when invoking a generic method through a delegate are determined when the
12delegate is instantiated. The type arguments can be given explicitly via a type-argument-list, or determined
13by type inference (§26.6.4). If type inference is used, the parameter types of the delegate are used as
14argument types in the inference process. The return type of the delegate is not used for inference. [Example:
15The following example shows both ways of supplying a type argument to a delegate instantiation
16expression:
17delegate int D(string s, int i);
18delegate int E();
19class X
20{
21 |
public static |
T F<T>(string s, T t) {…} |
||
22 |
public static T G<T>() {…} |
|
||
23 |
static void Main() { |
|
||
24 |
D d1 |
= new D(F<int>); |
// Ok, type argument given explicitly |
|
25 |
D d2 |
= new D(F); |
// Ok, int inferred as type argument |
|
26 |
E e1 |
= new E(G<int>); |
// Ok, type argument given explicitly |
|
27 |
E e2 |
= new E(G); |
// Error, cannot infer from return type |
|
28}
29}
30end example]
31Whenever a generic method is used to create delegate instance, type arguments are given or inferred when
32the delegate instance is created, and a type-argument-list shall not be supplied when the delegate is invoked
33(§22.3).
3426.6.6 No generic properties, events, indexers, operators, constructors, or destructors
35Properties, events, indexers, operators, constructors, and destructors shall not themselves have type
36parameters (although they can occur in generic types, and use the type parameters from an enclosing type).
3726.7 Constraints
38Generic type and method declarations can optionally specify type parameter constraints by including a type-
39parameter-constraints-clauses in the declaration.
40type-parameter-constraints-clauses:
41 |
type-parameter-constraints-clause |
42 |
type-parameter-constraints-clauses type-parameter-constraints-clause |
43 |
type-parameter-constraints-clause: |
44 |
where type-parameter : type-parameter-constraints |
415
|
C# LANGUAGE SPECIFICATION |
1 |
type-parameter-constraints: |
2 |
primary-constraint |
3 |
secondary-constraints |
4 |
constructor-constraint |
5 |
primary-constraint , secondary-constraints |
6 |
primary-constraint , constructor-constraint |
7 |
secondary-constraints , constructor-constraint |
8 |
primary-constraint , secondary-constraints , constructor-constraint |
9 |
primary-constraint: |
10 |
class-type |
11 |
class |
12struct
13secondary-constraints:
14 |
interface-type |
15 |
type-parameter |
16 |
secondary-constraints , interface-type |
17 |
secondary-constraints , type-parameter |
18 constructor-constraint:
19new ( )
20Each type-parameter-constraints-clause consists of the token where, followed by the name of a type
21parameter, followed by a colon and the list of constraints for that type parameter. There shall be at most one
22where clause for each type parameter, and the where clauses can be listed in any order. Like the get and
23set tokens in a property accessor, the where token is not a keyword.
24The list of constraints given in a where clause can include any of the following components, in this order: a
25single primary constraint, one or more secondary constraints, and the constructor constraint, new().
26A primary constraint can be a class type or the reference type constraint class or the value type constraint
27struct. A secondary constraint can be a type-parameter or interface-type.
28The reference type constraint specifies that a type argument used for the type parameter must be a reference
29type (§26.7.1). Any class type, interface type, delegate type, array type, or type parameter known to be a
30reference type (as defined below) satisfies this constraint.
31The value type constraint specifies that a type argument used for the type parameter must be a value type
32(§26.7.1). Any struct type, enum type, or type parameter having the value type constraint satisfies this
33constraint. A type parameter having the value type constraint shall not also have the constructor-constraint.
34Pointer types are never allowed to be type arguments so are not considered to satisfy either the reference
35type or value type constraints.
36If a constraint is a class type, an interface type, or a type parameter, that type specifies a minimal “base type”
37that every type argument used for that type parameter shall support. Whenever a constructed type or generic
38method is used, the type argument is checked against the constraints on the type parameter at compile-time.
39The type argument supplied shall derive from or implement all of the constraints given for that type
40parameter.
41A class-type constraint shall satisfy the following rules:
42• The type shall be a class type.
43• The type shall not be sealed.
44• The type shall not be one of the following types: System.Array, System.Delegate, System.Enum,
45or System.ValueType.
46• The type shall not be object. [Note: Since all types derive from object, such a constraint would have
47no effect if it were permitted. end note]
416
Chapter 26 Generics
1• At most one constraint for a given type parameter can be a class type.
2A type specified as an interface-type constraint shall satisfy the following rules:
3• The type shall be an interface type.
4• A type shall not be specified more than once in a given where clause.
5In either case, the constraint can involve any of the type parameters of the associated type or method
6declaration as part of a constructed type, and can involve the type being declared.
7Any class or interface type specified as a type parameter constraint shall be at least as accessible (§10.5.4) as
8the generic type or method being declared.
9A type specified as a type-parameter constraint shall satisfy the following rules:
10• The type shall be a type parameter.
11• A type shall not be specified more than once in a given where clause.
12In addition there shall be no cycles in the dependency graph of type parameters, where dependency is a
13transitive relation defined by:
14• If a type parameter T is used as a constraint for type parameter S then S depends on T.
15• If a type parameter S depends on a type parameter T and T depends on a type paremeter U then S
16depends on U.
17Given this relation, it is a compile-time error for a type parameter to depend on itself (directly or indirectly).
18Any constraints must be consistent among dependent type parameters. If type parameter S depends on type
19parameter T then:
20• T must not have the value type constraint. Otherwise, T is effectively sealed so S would be forced to be
21the same type as T, eliminating the need for two type parameters.
22• If S has the value type constraint then T must not have a class-type constraint.
23• If S has a class-type constraint A and T has a class-type constraint B then there must be an identity
24conversion or implicit reference conversion from A to B or an implicit reference conversion from B to A.
25• If S also depends on type parameter U and U has a class-type constraint A and T has a class-type
26constraint B then there must be an identity conversion or implicit reference conversion from A to B or an
27implicit reference conversion from B to A.
28It is valid for S to have the value type constraint and T to have the reference type constraint. Effectively this
29limits T to the types System.Object, System.ValueType, System.Enum and any interface type.
30If the where clause for a type parameter includes a constructor constraint (which has the form new()), it is
31possible to use the new operator to create instances of the type (§14.5.10.1). Any type argument used for a
32type parameter with a constructor constraint shall have a public parameterless constructor (this includes all
33value types) or be a type parameter having the value type constraint or constructor constraint (see §26.7.1 for
34details).
35[Example: The following are examples of constraints:
36interface IPrintable
37{
38void Print();
39}
40interface IComparable<T>
41{
42int CompareTo(T value);
43}
44interface IKeyProvider<T>
45{
417
C# LANGUAGE SPECIFICATION
1T GetKey();
2}
3class Printer<T> where T: IPrintable {…}
4class SortedList<T> where T: IComparable<T> {…}
5class Dictionary<K, V>
6 |
where K: IComparable<K> |
7where V: IPrintable, IKeyProvider<K>, new()
8{
9…
10}
11The following example is in error because it causes a circularity in the dependency graph of the type
12parameters:
13class Circular<S, T>
14 |
where S: T |
15where T: S // Error – circularity in dependency graph
16{...}
17The following examples illustrate additional invalid situations:
18class Sealed<S, T>
19 |
where |
S: |
T |
20 |
where |
T: |
struct // Error – T is sealed |
21{...}
22class A {...}
23class B {...}
24class Incompat<S, T>
25 |
where S: A, T |
26where T: B // Error – incompatible class-type constraints
27{...}
28class StructWithClass<S, T, U>
29 |
where |
S: |
struct, T |
30 |
where |
T: |
U |
31where U: A // Error – A incompatible with struct
32{...}
33end example]
34The effective base class of a type parameter T is defined as follows:
35• If T has no primary constraints or type parameter constraints, its effective base class is object.
36• If T has the value type constraint, its effective base class is System.ValueType.
37• If T has a class-type constraint C but no type-parameter constraints, its effective base class is C.
38• If T has no class-type constraint but has one or more type-parameter constraints, its effective base class
39is the most encompassed type (§13.4.2) in the set of effective base classes of its type-parameter
40constraints. The consistency rules ensure that such a most encompassed type exists.
41• If T has both a class-type constraint and one or more type-parameter constraints, its effective base class
42is the most encompassed type (§13.4.2) in the set consisting of the class-type constraint of T and the
43effective base classes of its type-parameter constraints. The consistency rules ensure that such a most
44encompassed type exists.
45The effective interface set of a type parameter T is defined as follows:
46• If T has no secondary-constraints, its effective interface set is empty.
47• If T has interface-type constraints but no type-parameter constraints, its effective interface set is its set
48of interface-type constraints.
49• If T has no interface-type constraints but has type-parameter constraints, its effective interface set is the
50union of the effective interface sets of its type-parameter constraints.
418
