- •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 |
1 |
if (key.CompareTo(x) < 0) {…} |
2 |
… |
3}
4}
58.16.5 Generic methods
6In some cases, a type parameter is not needed for an entire class, but only when calling a particular method.
7Often, this occurs when creating a method that takes a generic type as a parameter. For example, when using
8the Stack described earlier, we might often find ourselves pushing multiple values in a row onto a stack,
9and decide to write a method to do so in a single call. If we are only using a single kind of Stack, say
10Stack<int>, writing such a method is easy:
11static void PushMultiple(Stack<int> s, params int[] values) {
12 |
foreach (int v in values) { |
13 |
s.Push(v); |
14}
15}
16We can use this method to push multiple int values onto a Stack<int>:
17Stack<int> s = new Stack<int>();
18PushMultiple(s, 1, 2, 3, 4);
19However, the method above only works with one particular constructed type: Stack<int>. While we can
20easily write similar code for other constructed Stack types, we would like to write a single method that can
21work with any Stack, no matter what type argument was used.
22We do this by writing a generic method. Like a generic class declaration, a generic method is written with
23type parameters enclosed in angle brackets. With a generic method, the type parameters are written
24immediately after the method name, and can be used within the parameter list, return type, and body of the
25method. A generic PushMultiple method would look like this:
26static void PushMultiple<ItemType>(Stack<ItemType> s,
27 |
params ItemType[] values) |
28 |
{ |
29 |
foreach (ItemType v in values) { |
30 |
s.Push(v); |
31}
32}
33Using this generic method, we can now push multiple items onto a Stack of any kind. Furthermore, the
34compiler type checking will ensure that the pushed items have the correct type for the kind of Stack being
35used. When calling a generic method, we place type arguments to the method in angle brackets. The generic
36PushMultiple method can be called this way:
37Stack<int> s = new Stack<int>();
38PushMultiple<int>(s, 1, 2, 3, 4);
39This generic PushMultiple method is much better than the previous version, since it works on any kind of
40Stack. However, it appears to be less convenient to call, since the desired ItemType shall be supplied as a
41type argument to the method. In many cases, however, the compiler can deduce the correct type argument
42from the other arguments passed to the method, using a process called type inferencing. In the example
43above, since the first regular argument is of type Stack<int>, and the subsequent arguments are of type
44int, the compiler can reason that the type parameter shall also be int. Thus, the generic PushMultiple
45method can be called without specifying the type parameter:
46Stack<int> s = new Stack<int>();
47PushMultiple(s, 1, 2, 3, 4);
488.17 Anonymous methods
49In C# code, a callback method is often invoked strictly through a delegate and not invoked directly. The
50purpose of such a method is obscured by the necessary separation of the method declaration from the
51delegate instantiation. In contrast, the body of an anonymous method is written “in-line” where the delegate
52is used, conveniently tying the method source code to the delegate instance. Besides this convenience,
56
Chapter 8 Language overview
1anonymous methods have shared access to the local state of the containing function member. To achieve the
2same state sharing using named methods requires “lifting” local variables into fields of some object, further
3obscuring the source code.
4An anonymous method is declared using an anonymous-method-expression:
5anonymous-method-expression:
6 |
delegate anonymous-method-signatureopt block |
7The optional anonymous-method-signature defines the names and types of the formal parameters for the
8anonymous method. If the anonymous-method-signature is omitted, the block does not use any formal
9parameters. The block defines the body of the anonymous method.
10An anonymous-method-expression is classified as a special kind of value that references the anonymous
11method. This value has no instrinsic type, but is implicitly convertible to any delegate type that has
12parameter types and a return type compatible with the anonymous method. If an anonymous method is
13declared without a signature, any delegate parameter types that do not include an out parameter are
14compatible with the anonymous method. If an anonymous method is declared with a signature, only delegate
15parameter types that exactly match in type and order are compatible. The return type of a delegate is
16compatible with an anonymous method if the expressions associated with all return statements in the
17anonymous method can be implicitly converted to the return type of the delegate. A void delegate return
18type is compatible with an anonymous method that has no return statements, or only has return
19statements with no expression.
20Local variables and value parameters (including this) whose scope contains an anonymous method
21declaration are called outer variables of the anonymous method.
22In the absence of anonymous methods, the lifetime of a local variable or value parameter ends when
23execution of its scope ends, as described in §12.1.7. However, an anonymous method can access an outer
24variable instance after execution has left the scope of the outer variable. In this case, the lifetime of the outer
25variable extends until all referencing anonymous method delegates are eligible for garbage collection, as
26described in §10.9.
27An anonymous method cannot access ref or out parameters of an outer scope. The reason for this is that
28the caller of a function member allocates the storage for such parameters, so their lifetimes cannot be
29extended arbitrarily by the called function member. Consequently, since the this value of an instance
30method of a struct is equivalent to a ref parameter, an anonymous method in a struct is not allowed to
31access this.
32Semantically, an anonymous method contained in a class or struct T is considered to be a method of T. If T is
33a class type, the anonymous method is considered to be an instance method or static method according to
34whether the containing function member is instance or static, respectively. In contrast, if T is a struct type,
35the anonymous method is always considered to be static and, as indicated above, cannot access this.
36The following code defines an Action delegate type and a Walk method. The Walk method invokes an
37action sequentially on nodes in a linked list until either the action returns false or the end of the list is
38encountered.
39delegate bool Action(Node n);
40static void Walk(Node n, Action a) {
41while (n != null && a(n)) n = n.Next;
42}
43The following invocation of Walk employs an anonymous method to display the names of the nodes in a
44list:
45Walk(list,
46 |
delegate(Node n) { |
47 |
Console.WriteLine(n.Name); |
48 |
return true; |
49}
50);
57
C# LANGUAGE SPECIFICATION
1This code could easily be implemented using a named method, but doing so would require separating the
2method declaration from the invocation, obscuring the purpose of the method and the result of the
3invocation:
4Walk(list, new Action(DisplayNodeName));
5…
6bool DisplayNodeName(Node n) {
7 Console.WriteLine(n.Name);
8return true;
9}
10The following code uses an outer local variable c to display the ordinal position of each node:
11int c = 0;
12Walk(list,
13 |
delegate(Node n) { |
14 |
Console.WriteLine("{0}: {1}", ++c, n.Name); |
15 |
return true; |
16}
17);
18Console.WriteLine("Processed {0} nodes", c);
19Implementing this example using a named method would require “lifting” the outer local variable c into a
20field, which would further obscure the code, would introduce additional overhead in the type, and could
21introduce concurrency issues.
22The following code uses an outer local variable c and an instance field max to restrict the number of items
23displayed:
24class A
25{
26 |
int max; |
27 |
… |
28 |
void F(Node list) { |
29 |
int c = 0; |
30 |
Walk(list, |
31 |
delegate(Node n) { |
32 |
if (c >= max) { |
33 |
Console.WriteLine("... display truncated"); |
34 |
return false; |
35 |
} |
36 |
Console.WriteLine("{0}: {1}", ++c, n.name); |
37 |
return true; |
38 |
} |
39 |
); |
40 |
Console.WriteLine("Processed {0} nodes", c); |
41}
42}
43Since F is an instance method of class A, the anonymous method is considered to be an instance method
44of A, and the field max is accessed through the anonymous method’s this variable (which is the same as
45F’s this variable). That is, max is a field, not an outer variable, and the anonymous method can access max
46just as any other instance method does.
47Implementing this example in a safe way (considering the possibility of concurrency) without an anonymous
48method requires a significant amount of work and decreases clarity:
49class A
50{
51 |
int max; |
52 |
… |
53 |
void F(node list) { |
54 |
NodeNameDisplayer nnd = new NodeNameDisplayer(this); |
55 |
nnd.c = 0; |
58
|
Chapter 8 Language overview |
1 |
Walk(list, new Action(nnd.DisplayNodeName)); |
2 |
Console.WriteLine("Processed {0} nodes", nnd.c); |
3 |
} |
4 |
private class NodeNameDisplayer |
5 |
{ |
6 |
A outer; |
7 |
internal int c; |
8 |
NodeNameDisplayer(A outer) { |
9 |
this.outer = outer; |
10 |
} |
11 |
bool DisplayNodeName(Node n) { |
12 |
if (c >= outer.max) { |
13 |
Console.WriteLine("... display truncated"); |
14 |
return false; |
15 |
} |
16 |
Console.WriteLine("{0}: {1}", ++c, n.Name); |
17 |
return true; |
18 |
} |
19}
20}
218.18 Iterators
22The foreach statement is used to iterate over the elements of an enumerable collection. In order to be
23enumerable, a collection shall have a parameterless GetEnumerator method that returns an enumerator.
24Generally, enumerators are difficult to implement, but the task is significantly simplified with iterators.
25An iterator is a statement block that yields an ordered sequence of values. An iterator is distinguished from a
26normal statement block by the presence of one or more yield statements:
27• The yield return statement produces the next value of the iteration.
28• The yield break statement indicates that the iteration is complete.
29An iterator can be used as the body of a function member as long as the return type of the function member
30is one of the enumerator interfaces or one of the enumerable interfaces:
31• The enumerator interfaces are System.Collections.IEnumerator and types constructed from
32System.Collections.Generic.IEnumerator<T>.
33• The enumerable interfaces are System.Collections.IEnumerable and types constructed from
34System.Collections.Generic.IEnumerable<T>.
35It is important to understand that an iterator is not a kind of member, but is a means of implementing a
36function member. A member implemented via an iterator can be overridden or overloaded by other members
37which may or may not be implemented with iterators.
38The following Stack<T> class implements its GetEnumerator method using an iterator, which
39enumerates the elements of the stack in top-to-bottom order.
40using System.Collections.Generic;
41public class Stack<T>: IEnumerable<T>
42{
43 |
T[] items; |
44 |
int count; |
45 |
public void Push(T data) {…} |
46 |
public T Pop() {…} |
47 |
public IEnumerator<T> GetEnumerator() { |
48 |
for (int i = count – 1; i >= 0; --i) { |
49 |
yield return items[i]; |
50 |
} |
51}
52}
59
C# LANGUAGE SPECIFICATION
1The presence of the GetEnumerator method makes Stack<T> an enumerable type, allowing instances of
2Stack<T> to be used in a foreach statement. The following example pushes the values 0 through 9 onto
3an integer stack and then uses a foreach loop to display the values in top-to-bottom order.
4using System;
5class Test
6{
7 |
static void Main() { |
8 |
Stack<int> s = new Stack<int>(); |
9 |
for (int i = 0; i < 10; i++) s.Push(i); |
10 |
foreach (int i in s) Console.Write("{0} ", i); |
11 |
Console.WriteLine(); |
12}
13}
14The output of the example is:
159 8 7 6 5 4 3 2 1 0
16The foreach statement implicitly calls a collection’s parameterless GetEnumerator method to obtain an
17enumerator. There can only be one such parameterless GetEnumerator method defined by a collection, yet
18it is often appropriate to have multiple ways of enumerating, and ways of controlling the enumeration
19through parameters. In such cases, a collection can use iterators to implement properties or methods that
20return one of the enumerable interfaces. For example, Stack<T> might introduce two new properties,
21TopToBottom and BottomToTop, of type IEnumerable<T>:
22using System.Collections.Generic;
23public class Stack<T>: IEnumerable<T>
24{
25 |
T[] items; |
26 |
int count; |
27 |
public void Push(T data) {…} |
28 |
public T Pop() {…} |
29 |
public IEnumerator<T> GetEnumerator() { |
30 |
for (int i = count – 1; i >= 0; --i) { |
31 |
yield return items[i]; |
32 |
} |
33 |
} |
34 |
public IEnumerable<T> TopToBottom { |
35 |
get { |
36 |
return this; |
37 |
} |
38 |
} |
39 |
public IEnumerable<T> BottomToTop { |
40 |
get { |
41 |
for (int i = 0; i < count; i++) { |
42 |
yield return items[i]; |
43 |
} |
44 |
} |
45}
46}
47The get accessor for the TopToBottom property just returns this since the stack itself is an enumerable.
48The BottomToTop property returns an enumerable implemented with an iterator. The following example
49shows how the properties can be used to enumerate stack elements in either order:
50using System;
51class Test
52{
53 |
static void Main() { |
54 |
Stack<int> s = new Stack<int>(); |
55 |
for (int i = 0; i < 10; i++) s.Push(i); |
60
|
|
|
Chapter 8 Language overview |
1 |
foreach |
(int i in |
s.TopToBottom) Console.Write("{0} ", i); |
2 |
Console.WriteLine(); |
||
3 |
foreach |
(int i in |
s.BottomToTop) Console.Write("{0} ", i); |
4 |
Console.WriteLine(); |
||
5}
6}
7Of course, these properties can be used outside of a foreach statement as well. The following example
8passes the results of invoking the properties to a separate Print method. The example also shows an iterator
9used as the body of a FromToBy method that takes parameters:
10using System;
11using System.Collections.Generic;
12class Test
13{
14 |
static void Print(IEnumerable<int> collection) { |
15 |
foreach (int i in collection) Console.Write("{0} ", i); |
16 |
Console.WriteLine(); |
17 |
} |
18 |
static IEnumerable<int> FromToBy(int from, int to, int by) { |
19 |
for (int i = from; i <= to; i += by) { |
20 |
yield return i; |
21 |
} |
22 |
} |
23 |
static void Main() { |
24 |
Stack<int> s = new Stack<int>(); |
25 |
for (int i = 0; i < 10; i++) s.Push(i); |
26 |
Print(s.TopToBottom); |
27 |
Print(s.BottomToTop); |
28 |
Print(FromToBy(10, 20, 2)); |
29}
30}
31The output of the example is:
329 8 7 6 5 4 3 2 1 0
330 1 2 3 4 5 6 7 8 9
3410 12 14 16 18 20
35The generic and non-generic enumerable interfaces contain a single member, a GetEnumerator method
36that takes no arguments and returns an enumerator interface. An enumerable acts as an enumerator factory.
37Properly implemented enumerables generate independent enumerators each time their GetEnumerator
38method is called. Assuming the internal state of the enumerable has not changed between two calls to
39GetEnumerator, the two enumerators returned should produce the same set of values in the same order.
40This should hold even if the lifetimes of the enumerators overlap as in the following code sample:
41using System;
42using System.Collections.Generic;
43class Test
44{
45 |
static IEnumerable<int> FromTo(int from, int to) { |
46 |
while (from <= to) yield return from++; |
47 |
} |
48 |
static void Main() { |
49 |
IEnumerable<int> e = FromTo(1, 10); |
50 |
foreach (int x in e) { |
51 |
foreach (int y in e) { |
52 |
Console.Write("{0,3} ", x * y); |
53 |
} |
54 |
Console.WriteLine(); |
55 |
} |
56}
57}
61
C# LANGUAGE SPECIFICATION
1The code above prints a simple multiplication table of the integers 1 through 10. Note that the FromTo
2method is invoked only once to generate the enumerable e. However, e.GetEnumerator() is invoked
3multiple times (by the foreach statements) to generate multiple equivalent enumerators. These enumerators
4all encapsulate the iterator code specified in the declaration of FromTo. Note that the iterator code modifies
5the from parameter. Nevertheless, the enumerators act independently because each enumerator is given its
6own copy of the from and to parameters. The sharing of transient state between enumerators is one of
7several common subtle flaws that should be avoided when implementing enumerables and enumerators.
8Iterators are designed to help avoid these problems and to implement robust enumerables and enumerators in
9a simple intuitive way.
10End of informative text.
62
