
- •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
C# LANGUAGE SPECIFICATION
1An abstract event declaration specifies that the accessors of the event are virtual, but does not provide an
2actual implementation of the accessors. Instead, non-abstract derived classes are required to provide their
3own implementation for the accessors by overriding the event. Because an accessor for an abstract event
4declaration provides no actual implementation, its accessor-body simply consists of a semicolon.
5An event declaration that includes both the abstract and override modifiers specifies that the event is
6abstract and overrides a base event. The accessors of such an event are also abstract.
7Abstract event declarations are only permitted in abstract classes (§17.1.1.1).
8The accessors of an inherited virtual event can be overridden in a derived class by including an event
9declaration that specifies an override modifier. This is known as an overriding event declaration. An
10overriding event declaration does not declare a new event. Instead, it simply specializes the implementations
11of the accessors of an existing virtual event.
12An overriding event declaration shall specify the exact same accessibility modifiers, type, and name as the
13overridden event.
14An overriding event declaration can include the sealed modifier. Use of this modifier prevents a derived
15class from further overriding the event. The accessors of a sealed event are also sealed.
16It is a compile-time error for an overriding event declaration to include a new modifier.
17Except for differences in declaration and invocation syntax, virtual, sealed, override, and abstract accessors
18behave exactly like virtual, sealed, override and abstract methods. Specifically, the rules described in
19§17.5.3, §17.5.4, §17.5.5, and §17.5.6 apply as if accessors were methods of a corresponding form. Each
20accessor corresponds to a method with a single value parameter of the event type, a void return type, and
21the same modifiers as the containing event.
2217.8 Indexers
23An indexer is a member that enables an object to be indexed similar to an array. Indexers are declared using
24indexer-declarations:
25indexer-declaration:
26 |
attributesopt indexer-modifiersopt indexer-declarator { accessor-declarations } |
27 |
indexer-modifiers: |
28 |
indexer-modifier |
29 |
indexer-modifiers indexer-modifier |
30 |
indexer-modifier: |
31 |
new |
32 |
public |
33 |
protected |
34 |
internal |
35 |
private |
36 |
virtual |
37 |
sealed |
38 |
override |
39 |
abstract |
40extern
41indexer-declarator:
42 |
type |
this [ formal-parameter-list ] |
43 |
type |
interface-type . this [ formal-parameter-list ] |
44An indexer-declaration can include a set of attributes (§24) and a valid combination of the four access
45modifiers (§17.2.3), the new (§17.2.2), virtual (§17.5.3), override (§17.5.4), sealed (§17.5.5),
46abstract (§17.5.6), and extern (§17.5.7) modifiers.
304
Chapter 17 Classes
1Indexer declarations are subject to the same rules as method declarations (§17.5) with regard to valid
2combinations of modifiers, with the one exception being that the static modifier is not permitted on an
3indexer declaration.
4The modifiers virtual, override, and abstract are mutually exclusive except in one case. The
5abstract and override modifiers can be used together so that an abstract indexer can override a virtual
6one.
7The type of an indexer declaration specifies the element type of the indexer introduced by the declaration.
8Unless the indexer is an explicit interface member implementation, the type is followed by the keyword
9this. For an explicit interface member implementation, the type is followed by an interface-type, a “.”, and
10the keyword this. Unlike other members, indexers do not have user-defined names.
11The formal-parameter-list specifies the parameters of the indexer. The formal parameter list of an indexer
12corresponds to that of a method (§17.5.1), except that at least one parameter shall be specified, and that the
13ref and out parameter modifiers are not permitted.
14The type of an indexer and each of the types referenced in the formal-parameter-list shall be at least as
15accessible as the indexer itself (§10.5.4).
16The accessor-declarations (§17.6.2), which shall be enclosed in “{” and “}” tokens, declare the accessors
17of the indexer. The accessors specify the executable statements associated with reading and writing indexer
18elements.
19Even though the syntax for accessing an indexer element is the same as that for an array element, an indexer
20element is not classified as a variable. Thus, it is not possible to pass an indexer element as a ref or out
21argument.
22The formal-parameter-list of an indexer defines the signature (§10.6) of the indexer. Specifically, the
23signature of an indexer consists of the number and types of its formal parameters. The element type and
24names of the formal parameters are not part of an indexer’s signature.
25The signature of an indexer shall differ from the signatures of all other indexers declared in the same class.
26Indexers and properties are very similar in concept, but differ in the following ways:
27• A property is identified by its name, whereas an indexer is identified by its signature.
28• A property is accessed through a simple-name (§14.5.2) or a member-access (§14.5.4), whereas an
29indexer element is accessed through an element-access (§14.5.6.2).
30• A property can be a static member, whereas an indexer is always an instance member.
31• A get accessor of a property corresponds to a method with no parameters, whereas a get accessor of an
32indexer corresponds to a method with the same formal parameter list as the indexer.
33• A set accessor of a property corresponds to a method with a single parameter named value, whereas a
34set accessor of an indexer corresponds to a method with the same formal parameter list as the indexer,
35plus an additional parameter named value.
36• It is a compile-time error for an indexer accessor to declare a local variable or local constant with the
37same name as an indexer parameter.
38• In an overriding property declaration, the inherited property is accessed using the syntax base.P, where
39P is the property name. In an overriding indexer declaration, the inherited indexer is accessed using the
40syntax base[E], where E is a comma-separated list of expressions.
41Aside from these differences, all rules defined in §17.6.2 and §17.6.3 apply to indexer accessors as well as to
42property accessors.
43When an indexer declaration includes an extern modifier, the indexer is said to be an external indexer.
44Because an external indexer declaration provides no actual implementation, each of its accessor-
45declarations consists of a semicolon.
305
C# LANGUAGE SPECIFICATION
1[Example: The example below declares a BitArray class that implements an indexer for accessing the
2individual bits in the bit array.
3using System;
4class BitArray
5{
6 |
int[] bits; |
7 |
int length; |
8 |
public BitArray(int length) { |
9 |
if (length < 0) throw new ArgumentException(); |
10 |
bits = new int[((length - 1) >> 5) + 1]; |
11 |
this.length = length; |
12 |
} |
13 |
public int Length { |
14 |
get { return length; } |
15 |
} |
16 |
public bool this[int index] { |
17 |
get { |
18 |
if (index < 0 || index >= length) { |
19 |
throw new IndexOutOfRangeException(); |
20 |
} |
21 |
return (bits[index >> 5] & 1 << index) != 0; |
22 |
} |
23 |
set { |
24 |
if (index < 0 || index >= length) { |
25 |
throw new IndexOutOfRangeException(); |
26 |
} |
27 |
if (value) { |
28 |
bits[index >> 5] |= 1 << index; |
29 |
} |
30 |
else { |
31 |
bits[index >> 5] &= ~(1 << index); |
32 |
} |
33 |
} |
34}
35}
36An instance of the BitArray class consumes substantially less memory than a corresponding bool[]
37(since each value of the former occupies only one bit instead of the latter’s one byte), but it permits the same
38operations as a bool[].
39The following CountPrimes class uses a BitArray and the classical “sieve” algorithm to compute the
40number of primes between 2 and a given maximum:
41class CountPrimes
42{
43 |
static int Count(int max) { |
44 |
BitArray flags = new BitArray(max + 1); |
45 |
int count = 0; |
46 |
for (int i = 2; i <= max; i++) { |
47 |
if (!flags[i]) { |
48 |
for (int j = i * 2; j <= max; j += i) flags[j] = true; |
49 |
count++; |
50 |
} |
51 |
} |
52 |
return count; |
53 |
} |
54 |
static void Main(string[] args) { |
55 |
int max = int.Parse(args[0]); |
56 |
int count = Count(max); |
57 |
Console.WriteLine( |
58 |
"Found {0} primes between 2 and {1}", count, max); |
59}
60}
306