
- •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 17 Classes
1Note that the syntax for accessing elements of the BitArray is precisely the same as for a bool[]. end
2example]
3[Example: The following example shows a 26×10 grid class that has an indexer with two parameters. The
4first parameter is required to be an upperor lowercase letter in the range A–Z, and the second is required to
5be an integer in the range 0–9.
6using System;
7class Grid
8{
9 |
const int NumRows = 26; |
10 |
const int NumCols = 10; |
11 |
int[,] cells = new int[NumRows, NumCols]; |
12 |
|
13 |
public int this[char c, int colm] |
14 |
{ |
15 |
get { |
16 |
c = Char.ToUpper(c); |
17 |
if (c < 'A' || c > 'Z') { |
18 |
throw new ArgumentException(); |
19 |
} |
20 |
if (colm < 0 || colm >= NumCols) { |
21 |
throw new IndexOutOfRangeException(); |
22 |
} |
23 |
return cells[c - 'A', colm]; |
24 |
} |
25 |
set { |
26 |
c = Char.ToUpper(c); |
27 |
if (c < 'A' || c > 'Z') { |
28 |
throw new ArgumentException(); |
29 |
} |
30 |
if (colm < 0 || colm >= NumCols) { |
31 |
throw new IndexOutOfRangeException(); |
32 |
} |
33 |
cells[c - 'A', colm] = value; |
34 |
} |
35}
36}
37end example]
3817.8.1 Indexer overloading
39The indexer overload resolution rules are described in §14.4.2.
4017.9 Operators
41An operator is a member that defines the meaning of an expression operator that can be applied to instances
42of the class. Operators are declared using operator-declarations:
43operator-declaration:
44 |
attributesopt operator-modifiers operator-declarator operator-body |
45 |
operator-modifiers: |
46 |
operator-modifier |
47 |
operator-modifiers operator-modifier |
48 |
operator-modifier: |
49 |
public |
50 |
static |
51 |
extern |
307
|
C# LANGUAGE SPECIFICATION |
|
|
|
|
||||
1 |
operator-declarator: |
|
|
|
|
|
|||
2 |
unary-operator-declarator |
|
|
|
|
||||
3 |
binary-operator-declarator |
|
|
|
|
||||
4 |
conversion-operator-declarator |
|
|
|
|||||
5 |
unary-operator-declarator: |
|
|
|
|
||||
6 |
type operator overloadable-unary-operator ( type identifier ) |
||||||||
7 |
overloadable-unary-operator: one of |
|
|
||||||
8 |
+ |
- |
! |
~ |
++ |
-- |
|
true |
false |
9 |
binary-operator-declarator: |
|
|
|
|
||||
10 |
type operator overloadable-binary-operator ( type identifier , type identifier ) |
||||||||
11 |
overloadable-binary-operator: one of |
|
|
||||||
12 |
+ |
|
- |
* |
/ |
|
% |
|
|
13 |
& |
|
| |
^ |
|
|
|
|
|
14 |
<< |
|
right-shift |
|
|
|
|
|
|
15 |
== |
|
!= |
> |
< |
|
>= |
<= |
|
16 |
conversion-operator-declarator: |
|
|
|
|
||||
17 |
implicit operator type ( type identifier ) |
||||||||
18 |
explicit operator type ( type identifier ) |
||||||||
19 |
operator-body: |
|
|
|
|
|
|
||
20 |
block |
|
|
|
|
|
|
|
|
21;
22There are three categories of overloadable operators: Unary operators (§17.9.1), binary operators (§17.9.2),
23and conversion operators (§17.9.3).
24When an operator declaration includes an extern modifier, the operator is said to be an external operator.
25Because an external operator provides no actual implementation, its operator-body consists of a semi-colon.
26For all other operators, the operator-body consists of a block, which specifies the statements to execute
27when the operator is invoked. The block of an operator shall conform to the rules for value-returning
28methods described in §17.5.8.
29The following rules apply to all operator declarations:
30• An operator declaration shall include both a public and a static modifier.
31• The parameter(s) of an operator shall be value parameters. It is a compile-time error for an operator
32declaration to specify ref or out parameters.
33• The signature of an operator (§17.9.1, §17.9.2, §17.9.3) shall differ from the signatures of all other
34operators declared in the same class.
35• All types referenced in an operator declaration shall be at least as accessible as the operator itself
36(§10.5.4).
37• It is an error for the same modifier to appear multiple times in an operator declaration.
38Each operator category imposes additional restrictions, as described in the following subclauses.
39Like other members, operators declared in a base class are inherited by derived classes. Because operator
40declarations always require the class or struct in which the operator is declared to participate in the signature
41of the operator, it is not possible for an operator declared in a derived class to hide an operator declared in a
42base class. Thus, the new modifier is never required, and therefore never permitted, in an operator
43declaration.
44Additional information on unary and binary operators can be found in §14.2.
45Additional information on conversion operators can be found in §13.4.
308
Chapter 17 Classes
117.9.1 Unary operators
2The following rules apply to unary operator declarations, where T denotes the class or struct type that
3contains the operator declaration:
4• A unary +, -, !, or ~ operator shall take a single parameter of type T and can return any type.
5• A unary ++ or -- operator shall take a single parameter of type T and shall return type T or a type
6derived from T.
7• A unary true or false operator shall take a single parameter of type T and shall return type bool.
8The signature of a unary operator consists of the operator token (+, -, !, ~, ++, --, true, or false) and the
9type of the single formal parameter. The return type is not part of a unary operator’s signature, nor is the
10name of the formal parameter.
11The true and false unary operators require pair-wise declaration. A compile-time error occurs if a class
12declares one of these operators without also declaring the other. The true and false operators are
13described further in §14.16.
14[Example: The following example shows an implementation and subsequent usage of operator++ for an
15integer vector class:
16public class IntVector
17{
18 |
public |
int Length { … } |
// read-only property |
19 |
public |
int this[int index] { … } // read-write indexer |
|
20 |
public |
IntVector(int vectorLength) { … } |
|
21 |
public static IntVector operator++(IntVector iv) { |
||
22 |
IntVector temp = new IntVector(iv.Length); |
||
23 |
for (int i = 0; i < iv.Length; ++i) |
||
24 |
temp[i] = iv[i] + 1; |
|
|
25 |
return temp; |
|
26}
27}
28class Test
29{
30 |
static void Main() { |
|
31 |
IntVector iv1 = new IntVector(4); // vector of 4x0 |
|
32 |
IntVector iv2; |
|
33 |
|
|
34 |
iv2 = iv1++; |
// iv2 contains 4x0, iv1 contains 4x1 |
35 |
iv2 = ++iv1; |
// iv2 contains 4x2, iv1 contains 4x2 |
36}
37}
38Note how the operator method returns the value produced by adding 1 to the operand, just like the postfix
39increment and decrement operators (§14.5.9), and the prefix increment and decrement operators (§14.6.5).
40Unlike in C++, this method need not, and, in fact, should not, modify the value of its operand directly. end
41example]
4217.9.2 Binary operators
43A binary operator shall take two parameters, at least one of which shall have the class or struct type in which
44the operator is declared. The shift operators (§14.8) are further constrained: The type of the first parameter
45shall be the class or struct type in which the operator is declared, and the second parameter shall always have
46the type int. A binary operator can return any type.
47The signature of a binary operator consists of the operator token (+, -, *, /, %, &, |, ^, <<, right-shift, ==,
48!=, >, <, >=, or <=) and the types of the two formal parameters. The return type and the names of the formal
49parameters are not part of a binary operator’s signature.
50Certain binary operators require pair-wise declaration. For every declaration of either operator of a pair,
51there shall be a matching declaration of the other operator of the pair. Two operator declarations match when
309
C# LANGUAGE SPECIFICATION
1they have the same return type and the same type for each parameter. The following operators require pair-
2wise declaration:
3• operator == and operator !=
4• operator > and operator <
5• operator >= and operator <=
617.9.3 Conversion operators
7A conversion operator declaration introduces a user-defined conversion operator (§13.4), which augments
8the pre-defined implicit and explicit conversions.
9A conversion operator declaration that includes the implicit keyword introduces a user-defined implicit
10conversion operator. Implicit conversions can occur in a variety of situations, including function member
11invocations, cast expressions, and assignments. This is described further in §13.1.
12A conversion operator declaration that includes the explicit keyword introduces a user-defined explicit
13conversion operator. Explicit conversions can occur in cast expressions, and are described further in §13.2.
14A conversion operator converts from a source type, indicated by the parameter type of the conversion
15operator, to a target type, indicated by the return type of the conversion operator. A class or struct is
16permitted to declare a conversion operator from a source type S to a target type T provided all of the
17following are true:
18• S and T are different types.
19• Either S or T is the class or struct type in which the operator declaration takes place.
20• Neither S nor T is object or an interface-type.
21• T is not a base class of S, and S is not a base class of T.
22From the second rule it follows that a conversion operator shall convert either to or from the class or struct
23type in which the operator is declared. [Example: It is possible for a class or struct type C to define a
24conversion from C to int and from int to C, but not from int to bool. end example]
25It is not possible to redefine a pre-defined conversion. Thus, conversion operators are not allowed to convert
26from or to object because implicit and explicit conversions already exist between object and all other
27types. Likewise, neither the source nor the target types of a conversion can be a base type of the other, since
28a conversion would then already exist.
29User-defined conversions are not allowed to convert from or to interface-types. In particular, this restriction
30ensures that no user-defined transformations occur when converting to an interface-type, and that a
31conversion to an interface-type succeeds only if the object being converted actually implements the specified
32interface-type.
33The signature of a conversion operator consists of the source type and the target type. (This is the only form
34of member for which the return type participates in the signature.) The implicit or explicit
35classification of a conversion operator is not part of the operator’s signature. Thus, a class or struct cannot
36declare both an implicit and an explicit conversion operator with the same source and target types.
37[Note: In general, user-defined implicit conversions should be designed to never throw exceptions and never
38lose information. If a user-defined conversion can give rise to exceptions (for example, because the source
39argument is out of range) or loss of information (such as discarding high-order bits), then that conversion
40should be defined as an explicit conversion. end note]
41[Example: In the following code
42using System;
43public struct Digit
44{
45 |
byte value; |
310