- •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• If T has both interface-type constraints and type-parameter constraints, its effective interface set is the
2union of its set of interface-type constraints and the effective interface sets of its type-parameter
3constraints.
4A type parameter is known to be a reference type if it has the reference type constraint or its effective base
5class is not object or System.ValueType.
6Values of a constrained type parameter type can be used to access the instance members implied by the
7constraints. [Example: In the following code
8interface IPrintable
9{
10void Print();
11}
12class Printer<T> where T: IPrintable
13{
14 |
void PrintOne(T x) { |
15 |
x.Print(); |
16}
17}
18the methods of IPrintable can be invoked directly on x because T is constrained to always implement
19IPrintable. end example]
20Two generic partial type declarations (in the same program) contribute to the same unbound generic type if
21they have the same fully qualified name (which includes the number of type parameters) (§10.3). Two such
22partial type declarations shall specify the same name for each type parameter, in order.
23When a partial generic type declaration includes constraints, the constraints shall agree with all other parts
24that include constraints. Specifically, each part that includes constraints shall have constraints for the same
25set of type parameters, and for each type parameter, the sets of primary, secondary, and constructor
26constraints shall be equivalent. Two sets of constraints are equivalent if they contain the same members. If
27no part of a partial generic type specifies type parameter constraints, the type parameters are considered
28unconstrained. [Example:
29partial class Map<K,V>
30 |
where K: IComparable<K> |
31where V: IKeyProvider<K>, new()
32{
33...
34}
35partial class Map<K,V>
36 |
where V: IKeyProvider<K>, new() |
37where K: IComparable<K>
38{
39...
40}
41partial class Map<K,V>
42{
43...
44}
45is correct because those parts that include constraints (the first two) effectively specify the same set of
46primary, secondary, and constructor constraints for the same set of type parameters, respectively. end
47example]
4826.7.1 Satisfying constraints
49Whenever a constructed type or generic method is referenced, the supplied type arguments are checked
50against the type parameter constraints declared on the generic type or method. For each where clause, the
51type argument A that corresponds to the named type parameter is checked against each constraint as follows:
419
C# LANGUAGE SPECIFICATION
1• If the constraint is a class type, an interface type, or a type parameter, let C represent that constraint with
2the supplied type arguments substituted for any type parameters that appear in the constraint. To satisfy
3the constraint, it shall be the case that type A is convertible to type C by one of the following:
4o An identity conversion (§13.1.1)
5o An implicit reference conversion (§13.1.4)
6o A boxing conversion (§13.1.5)
7o An implicit conversion from a type parameter A to C (§26.7.4).
8• If the constraint is the reference type constraint, the type A must satisfy one of the following:
9o A is an interface type, class type, delegate type or array type. [Note: Note that System.ValueType
10and System.Enum are reference types so satisfy this constraint. end note]
11o A is a type parameter that is known to be a reference type (§26.7).
12• If the constraint is the value type constraint, the type A must satisfy one of the following:
13o A is a struct type or enum type. [Note: Note that System.ValueType and System.Enum are
14reference types so do not satisfy this constraint. end note]
15o A is a type parameter having the value type constraint (§26.7).
16• If the constraint is the constructor constraint new(), the type argument A shall not be abstract and
17shall have a public parameterless constructor. This is satisfied if one of the following is true:
18o A is a value type, since all value types have a public default constructor (§11.1.2).
19o A is a type parameter having the value type constraint (§26.7).
20o A is a class that is not abstract, A contains an explicitly declared public constructor with no
21parameters.
22o A is not abstract and has a default constructor (§17.10.4).
23A compile-time error occurs if one or more of a type parameter’s constraints are not satisfied by the given
24type arguments.
25Since type parameters are not inherited, constraints are never inherited either. [Example: In the code below,
26D needs to specify the constraint on its type parameter T, so that T satisfies the constraint imposed by the
27base class B<T>. In contrast, class E need not specify a constraint, because List<T> implements
28IEnumerable for any T.
29class B<T> where T: IEnumerable {…}
30class D<T>: B<T> where T: IEnumerable {…}
31class E<T>: B<List<T>> {…}
32end example]
3326.7.2 Member lookup on type parameters
34The results of member lookup in a type given by a type parameter T depends on the constraints, if any,
35specified for T. If T has no class-type, interface-type or type-parameter constraints, then member lookup on
36T returns the same set of members as member lookup on object. Otherwise, the first stage of member
37lookup (§14.3) considers all the members in the effective base class of T and all the members in each
38interface in the effective interface set of T. After performing the first stage of member lookup for each of
39theses types, the results are combined, and then hidden members are removed from the combined results.
40Before the advent of generics, member lookup always returned either a set of members declared solely in
41classes, or a set of members declared solely in interfaces and possibly the type object. Member lookup on
42type parameters changes this somewhat. When a type parameter has both an effective base class other than
43object and a non-empty effective interface set, member lookup can return a set of members, some of which
420
Chapter 26 Generics
1were declared in a class, and others of which were declared in an interface. The following additional rules
2handle this case.
3• As specified in §14.3, during member lookup, members declared in a class other than object hide
4members declared in interfaces.
5• During overload resolution of methods (§14.5.5.1) and indexers (§14.5.6.2), if any applicable member
6was declared in a class other than object, all members declared in an interface are removed from the
7set of considered members.
8These rules only have effect when doing binding on a type parameter with both an effective base class other
9than object and a non-empty effective interface set. [Note: Informally, members defined in a class
10constraint are preferred over members in an interface constraint. end note]
1126.7.3 Type parameters and boxing
12When a struct type overrides a virtual method inherited from System.Object (such as Equals,
13GetHashCode, or ToString), invocation of the virtual method through an instance of the struct type
14doesn’t cause boxing to occur. This is true even when the struct is used as a type parameter and the
15invocation occurs through an instance of the type parameter type. [Example:
16using System;
17struct Counter
18{
19 |
int value; |
20 |
public override string ToString() { |
21 |
value++; |
22 |
return value.ToString(); |
23}
24}
25class Program
26{
27 |
static void Test<T>() where T: new() { |
28 |
T x = new T(); |
29 |
Console.WriteLine(x.ToString()); |
30 |
Console.WriteLine(x.ToString()); |
31 |
Console.WriteLine(x.ToString()); |
32 |
} |
33 |
static void Main() { |
34 |
Test<Counter>(); |
35}
36}
37The output of the program is:
381
392
403
41Although it is bad style for ToString to have side effects, the example demonstrates that no boxing
42occurred for the three invocations of x.ToString(). end example]
43Similarly, boxing never implicitly occurs when accessing a member on a constrained type parameter.
44[Example: Suppose an interface ICounter contains a method Increment which can be used to modify a
45value. If ICounter is used as a constraint, the implementation of the Increment method is called with a
46reference to the variable that Increment was called on, never a boxed copy. This behaviour is different
47than the non-generic case. When making a call to an interface implementation on a struct type the argument
48is always boxed.
49using System;
50interface ICounter
51{
52void Increment();
53}
421
C# LANGUAGE SPECIFICATION
1struct Counter: ICounter
2{
3 |
int value; |
4 |
public override string ToString() { |
5 |
return value.ToString(); |
6 |
} |
7 |
void ICounter.Increment() { |
8 |
value++; |
9}
10}
11class Program
12{
13 |
static void Test<T>() where T: ICounter, new() { |
|
14 |
T x = new T(); |
|
15 |
Console.WriteLine(x); |
|
16 |
x.Increment(); |
// Modify x |
17 |
Console.WriteLine(x); |
|
18 |
((ICounter)x).Increment(); |
// Modify boxed copy of x |
19 |
Console.WriteLine(x); |
|
20 |
} |
|
21 |
static void Main() { |
|
22 |
Test<Counter>(); |
|
23}
24}
25The first call to Increment modifies the value in the variable x. This is not equivalent to the second call to
26Increment, which modifies the value in a boxed copy of x. Thus, the output of the program is:
270
281
291
30end example]
3126.7.4 Conversions involving type parameters
32The conversions that are allowed on a type parameter T depend on the constraints specified for T and are
33detailed in §13.
34The conversion rules do not permit a direct explicit conversion from an unconstrained type parameter to an
35arbitrary non-interface type, which might be surprising. The reason for this rule is to prevent confusion and
36make the semantics of such conversions clear. [Example: Consider the following declaration:
37class X<T>
38{
39 |
public static long |
F(T t) { |
40 |
return (long)t; |
// Error, explicit conversion not permitted |
41}
42}
43If the direct explicit conversion of t to long were permitted, one might easily expect that X<int>.F(7)
44would return 7L. However, it would not, because the standard numeric conversions are only considered
45when the types are known to be numeric at compile time. In order to make the semantics clear, the above
46example should be written:
47class X<T>
48{
49 |
public static long F(T t) { |
|
50 |
return (long)(object)t; |
// OK, conversions permitted |
51}
52}
53This code will now compile but executing X<int>.F(7) would then throw an exception at runtime, since a
54boxed int cannot be converted directly to a long.
55end example]
422
