
- •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 20 Interfaces
1a qualified interface member name for Paint is IControl.Paint and a qualified interface member name
2for SetText is ITextBox.SetText. In the example above, it is not possible to refer to Paint as
3ITextBox.Paint. end example]
4When an interface is part of a namespace, a qualified interface member name can include the namespace
5name. [Example:
6namespace System
7{
8 |
public interface ICloneable |
9 |
{ |
10 |
object Clone(); |
11}
12}
13Within the System namespace, both ICloneable.Clone and System.ICloneable.Clone are qualified
14interface member names for the Clone method. end example]
1520.4 Interface implementations
16Interfaces can be implemented by classes and structs. To indicate that a class or struct implements an
17interface, the interface is included in the base class list of the class or struct. [Example:
18interface ICloneable
19{
20object Clone();
21}
22interface IComparable
23{
24int CompareTo(object other);
25}
26class ListEntry: ICloneable, IComparable
27{
28 |
public object Clone() {…} |
29public int CompareTo(object other) {…}
30}
31end example]
32A class or struct that implements an interface also implicitly implements all of the interface’s base
33interfaces. This is true even if the class or struct doesn’t explicitly list all base interfaces in the base class
34list. [Example:
35interface IControl
36{
37void Paint();
38}
39interface ITextBox: IControl
40{
41void SetText(string text);
42}
43class TextBox: ITextBox
44{
45 |
public void Paint() {…} |
46public void SetText(string text) {…}
47}
48Here, class TextBox implements both IControl and ITextBox. end example]
4920.4.1 Explicit interface member implementations
50For purposes of implementing interfaces, a class or struct can declare explicit interface member
51implementations. An explicit interface member implementation is a method, property, event, or indexer
52declaration that references a qualified interface member name. [Example:
341
C# LANGUAGE SPECIFICATION
1interface ICloneable
2{
3object Clone();
4}
5interface IComparable
6{
7int CompareTo(object other);
8}
9class ListEntry: ICloneable, IComparable
10{
11 |
object ICloneable.Clone() {…} |
12int IComparable.CompareTo(object other) {…}
13}
14Here, ICloneable.Clone and IComparable.CompareTo are explicit interface member
15implementations. end example]
16[Example: In some cases, the name of an interface member might not be appropriate for the implementing
17class, in which case, the interface member can be implemented using explicit interface member
18implementation. A class implementing a file abstraction, for example, would likely implement a Close
19member function that has the effect of releasing the file resource, and implement the Dispose method of
20the IDisposable interface using explicit interface member implementation:
21interface IDisposable
22{
23void Dispose();
24}
25class MyFile: IDisposable
26{
27 |
void IDisposable.Dispose() |
28 |
{ |
29 |
Close(); |
30 |
} |
31 |
public void Close() |
32 |
{ |
33 |
// Do what's necessary to close the file |
34 |
System.GC.SuppressFinalize(this); |
35}
36}
37end example]
38It is not possible to access an explicit interface member implementation through a qualified interface
39member name in a method invocation, property access, event access, or indexer access. An explicit interface
40member implementation can only be accessed through an interface instance, and is in that case referenced
41simply by its member name.
42It is a compile-time error for an explicit interface member implementation to include any modifiers other
43than extern (§17.5). It is a compile-time error for an explicit interface method implementation to include
44type-parameter-constraints-clauses. The constraints for a generic explicit interface method implementation
45are inherited from the interface method.
46Explicit interface member implementations have different accessibility characteristics than other members.
47Because explicit interface member implementations are never accessible through a qualified interface
48member name in a method invocation or a property access, they are in a sense private. However, since they
49can be accessed through an interface instance, they are in a sense also public.
50Explicit interface member implementations serve two primary purposes:
51• Because explicit interface member implementations are not accessible through class or struct instances,
52they allow interface implementations to be excluded from the public interface of a class or struct. This is
53particularly useful when a class or struct implements an internal interface that is of no interest to a
54consumer of that class or struct.
342
Chapter 20 Interfaces
1• Explicit interface member implementations allow disambiguation of interface members with the same
2signature. Without explicit interface member implementations it would be impossible for a class or
3struct to have different implementations of interface members with the same signature and return type,
4as would it be impossible for a class or struct to have any implementation at all of interface members
5with the same signature but with different return types.
6For an explicit interface member implementation to be valid, the class or struct shall name an interface in its
7base class list that contains a member whose containing type, name, type, number of type parameters, and
8parameter types exactly match those of the explicit interface member implementation. If an interface
9function member has a parameter array, the corresponding parameter of an associated explicit interface
10member implementation is allowed, but not required, to have the params modifier. If the interface function
11member does not have a parameter array then an associated explicit interface member implementation shall
12not have a parmater array. [Example: Thus, in the following class
13class Shape: ICloneable
14{
15 |
object ICloneable.Clone() {…} |
16int IComparable.CompareTo(object other) {…} // invalid
17}
18the declaration of IComparable.CompareTo results in a compile-time error because IComparable is not
19listed in the base class list of Shape and is not a base interface of ICloneable. Likewise, in the
20declarations
21class Shape: ICloneable
22{
23object ICloneable.Clone() {…}
24}
25class Ellipse: Shape
26{
27object ICloneable.Clone() {…} // invalid
28}
29the declaration of ICloneable.Clone in Ellipse results in a compile-time error because ICloneable is
30not explicitly listed in the base class list of Ellipse. end example]
31The qualified interface member name of explicit interface member implementation shall reference the
32interface in which the member was declared. [Example: Thus, in the declarations
33interface IControl
34{
35void Paint();
36}
37interface ITextBox: IControl
38{
39void SetText(string text);
40}
41class TextBox: ITextBox
42{
43 |
void IControl.Paint() {…} |
44void ITextBox.SetText(string text) {…}
45}
46the explicit interface member implementation of Paint shall be written as IControl.Paint and not as
47ITextBox.Paint. end example]
4820.4.2 Interface mapping
49A class or struct shall provide implementations of all members of the interfaces that are listed in the base
50class list of the class or struct. The process of locating implementations of interface members in an
51implementing class or struct is known as interface mapping.
343
C# LANGUAGE SPECIFICATION
1Interface mapping for a class or struct C locates an implementation for each member of each interface
2specified in the base class list of C. The implementation of a particular interface member I.M, where I is the
3interface in which the member M is declared, is determined by examining each class or struct S, starting with
4C and repeating for each successive base class of C, until a match is located:
5• If S contains a declaration of an explicit interface member implementation that matches I and M, then
6this member is the implementation of I.M.
7• Otherwise, if S contains a declaration of a non-static public member that matches M, then this member is
8the implementation of I.M.
9A compile-time error occurs if implementations cannot be located for all members of all interfaces specified
10in the base class list of C. The members of an interface include those members that are inherited from base
11interfaces.
12Members of a constructed interface type are considered to have any type parameters replaced with the
13corresponding type arguments as specified in §26.5.4. [Example: For example, given the generic interface
14declaration:
15interface I<T>
16{
17 |
T F(int x, T[,] y); |
18T this[int y] { get; }
19}
20the constructed interface I<string[]> has the members:
21string[] F(int x, string[,][] y);
22string[] this[int y] { get; }
23end example]
24For purposes of interface mapping, a class member A matches an interface member B when:
25• A and B are methods, and the name, type, and formal parameter lists of A and B are identical.
26• A and B are properties, the name and type of A and B are identical, and A has the same accessors as B (A
27is permitted to have additional accessors if it is not an explicit interface member implementation).
28• A and B are events, and the name and type of A and B are identical.
29• A and B are indexers, the type and formal parameter lists of A and B are identical, and A has the same
30accessors as B (A is permitted to have additional accessors if it is not an explicit interface member
31implementation).
32Notable implications of the interface-mapping algorithm are:
33• Explicit interface member implementations take precedence over other members in the same class or
34struct when determining the class or struct member that implements an interface member.
35• Neither non-public nor static members participate in interface mapping.
36[Example: In the following code
37interface ICloneable
38{
39object Clone();
40}
41class C: ICloneable
42{
43 |
object ICloneable.Clone() {…} |
44public object Clone() {…}
45}
46the ICloneable.Clone member of C becomes the implementation of Clone in ICloneable because
47explicit interface member implementations take precedence over other members. end example]
344
Chapter 20 Interfaces
1If a class or struct implements two or more interfaces containing a member with the same name, type, and
2parameter types, it is possible to map each of those interface members onto a single class or struct member.
3[Example:
4interface IControl
5{
6void Paint();
7}
8interface IForm
9{
10void Paint();
11}
12class Page: IControl, IForm
13{
14public void Paint() {…}
15}
16Here, the Paint methods of both IControl and IForm are mapped onto the Paint method in Page. It is
17of course also possible to have separate explicit interface member implementations for the two methods. end
18example]
19If a class or struct implements an interface that contains hidden members, then some members shall
20necessarily be implemented through explicit interface member implementations. [Example:
21interface IBase
22{
23int P { get; }
24}
25interface IDerived: IBase
26{
27new int P();
28}
29An implementation of this interface would require at least one explicit interface member implementation,
30and would take one of the following forms
31class C: IDerived
32{
33 |
int IBase.P { get {…} } |
34int IDerived.P() {…}
35}
36class C: IDerived
37{
38 |
public int P { get {…} } |
39int IDerived.P() {…}
40}
41class C: IDerived
42{
43 |
int IBase.P { get {…} } |
44public int P() {…}
45}
46end example]
47When a class implements multiple interfaces that have the same base interface, there can be only one
48implementation of the base interface. [Example: In the following code
49interface IControl
50{
51void Paint();
52}
345