
- •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 |
1 |
public Digit(int value) { |
2 |
if (value < 0 || value > 9) throw new ArgumentException(); |
3 |
this.value = value; |
4 |
} |
5 |
public static implicit operator byte(Digit d) { |
6 |
return d.value; |
7 |
} |
8 |
public static explicit operator Digit(int n) { |
9 |
return new Digit(n); |
10}
11}
12the conversion operator from Digit to byte is implicit because it never throws exceptions or loses
13information, but the conversion operator from int to Digit is explicit since Digit can only represent a
14subset of the possible values of an int. end example]
1517.10 Instance constructors
16An instance constructor is a member that implements the actions required to initialize an instance of a class.
17Instance constructors are declared using constructor-declarations:
18constructor-declaration:
19 |
attributesopt constructor-modifiersopt constructor-declarator constructor-body |
20 |
constructor-modifiers: |
21 |
constructor-modifier |
22 |
constructor-modifiers constructor-modifier |
23 |
constructor-modifier: |
24 |
public |
25 |
protected |
26 |
internal |
27 |
private |
28extern
29constructor-declarator:
30 |
identifier ( formal-parameter-listopt ) constructor-initializeropt |
31 |
constructor-initializer: |
32 |
: base ( argument-listopt ) |
33 |
: this ( argument-listopt ) |
34 |
constructor-body: |
35 |
block |
36;
37A constructor-declaration can include a set of attributes (§24), a valid combination of the four access
38modifiers (§17.2.3), and an extern (§17.5.7) modifier. A constructor declaration is not permitted to include
39the same modifier multiple times.
40The identifier of a constructor-declarator shall name the class in which the instance constructor is declared.
41If any other name is specified, a compile-time error occurs.
42The optional formal-parameter-list of an instance constructor is subject to the same rules as the formal-
43parameter-list of a method (§17.5). The formal parameter list defines the signature (§10.6) of an instance
44constructor and governs the process whereby overload resolution (§14.4.2) selects a particular instance
45constructor in an invocation.
46Each of the types referenced in the formal-parameter-list of an instance constructor shall be at least as
47accessible as the constructor itself (§10.5.4).
48The optional constructor-initializer specifies another instance constructor to invoke before executing the
49statements given in the constructor-body of this instance constructor. This is described further in §17.10.1.
311
C# LANGUAGE SPECIFICATION
1When a constructor declaration includes an extern modifier, the constructor is said to be an external
2constructor.
3Because an external constructor declaration provides no actual implementation, its constructor-body consists
4of a semicolon. For all other constructors, the constructor-body consists of a block, which specifies the
5statements to initialize a new instance of the class. This corresponds exactly to the block of an instance
6method with a void return type (§17.5.8).
7Instance constructors are not inherited. Thus, a class has no instance constructors other than those actually
8declared in the class. If a class contains no instance constructor declarations, a default instance constructor is
9automatically provided (§17.10.4).
10Instance constructors are invoked by object-creation-expressions (§14.5.10.1) and through constructor-
11initializers.
1217.10.1 Constructor initializers
13All instance constructors (except those for class object) implicitly include an invocation of another
14instance constructor immediately before the constructor-body. The constructor to implicitly invoke is
15determined by the constructor-initializer:
16• An instance constructor initializer of the form base(argument-listopt) causes an instance constructor
17from the direct base class to be invoked. That constructor is selected using argument-list and the
18overload resolution rules of §14.4.2. The set of candidate instance constructors consists of all accessible
19instance constructors declared in the direct base class, or the default constructor (§17.10.4), if no
20instance constructors are declared in the direct base class. If this set is empty, or if a single best instance
21constructor cannot be identified, a compile-time error occurs.
22• An instance constructor initializer of the form this(argument-listopt) causes an instance constructor
23from the class itself to be invoked. The constructor is selected using argument-list and the overload
24resolution rules of §14.4.2. The set of candidate instance constructors consists of all accessible instance
25constructors declared in the class itself. If that set is empty, or if a single best instance constructor cannot
26be identified, a compile-time error occurs. If an instance constructor declaration includes a constructor
27initializer that invokes the constructor itself, a compile-time error occurs.
28If an instance constructor has no constructor initializer, a constructor initializer of the form base() is
29implicitly provided. [Note: Thus, an instance constructor declaration of the form
30C(…) {…}
31is exactly equivalent to
32C(…): base() {…}
33end note]
34The scope of the parameters given by the formal-parameter-list of an instance constructor declaration
35includes the constructor initializer of that declaration. Thus, a constructor initializer is permitted to access
36the parameters of the constructor. [Example:
37class A
38{
39public A(int x, int y) {}
40}
41class B: A
42{
43public B(int x, int y): base(x + y, x - y) {}
44}
45end example]
46An instance constructor initializer cannot access the instance being created. Therefore it is a compile-time
47error to reference this in an argument expression of the constructor initializer, as it is a compile-time error
48for an argument expression to reference any instance member through a simple-name.
312
Chapter 17 Classes
117.10.2 Instance variable initializers
2When an instance constructor has no constructor initializer, or it has a constructor initializer of the form
3base(…), that constructor implicitly performs the initializations specified by the variable-initializers of the
4instance fields declared in its class. This corresponds to a sequence of assignments that are executed
5immediately upon entry to the constructor and before the implicit invocation of the direct base class
6constructor. The variable initializers are executed in the textual order in which they appear in the class
7declaration (§17.4.5).
817.10.3 Constructor execution
9Variable initializers are transformed into assignment statements, and these assignment statements are
10executed before the invocation of the base class instance constructor. This ordering ensures that all instance
11fields are initialized by their variable initializers before any statements that have access to that instance are
12executed. [Example:
13using System;
14class A
15{
16 |
public A() { |
17 |
PrintFields(); |
18 |
} |
19public virtual void PrintFields() {}
20}
21class B: A
22{
23 |
int x = 1; |
24 |
int y; |
25 |
public B() { |
26 |
y = -1; |
27 |
} |
28 |
public override void PrintFields() { |
29 |
Console.WriteLine("x = {0}, y = {1}", x, y); |
30}
31}
32When new B() is used to create an instance of B, the following output is produced:
33x = 1, y = 0
34The value of x is 1 because the variable initializer is executed before the base class instance constructor is
35invoked. However, the value of y is 0 (the default value of an int) because the assignment to y is not
36executed until after the base class constructor returns.
37It is useful to think of instance variable initializers and constructor initializers as statements that are
38automatically inserted before the constructor-body. The example
39using System;
40using System.Collections;
41class A
42{
43 |
int x = 1, |
y = -1, count; |
44 |
public A() |
{ |
45 |
count = 0; |
|
46 |
} |
|
47 |
public A(int n) { |
|
48 |
count = n; |
49}
50}
313
C# LANGUAGE SPECIFICATION
1class B: A
2{
3 |
double sqrt2 = Math.Sqrt(2.0); |
4 |
ArrayList items = new ArrayList(100); |
5 |
int max; |
6 |
public B(): this(100) { |
7 |
items.Add("default"); |
8 |
} |
9 |
public B(int n): base(n – 1) { |
10 |
max = n; |
11}
12}
13contains several variable initializers; it also contains constructor initializers of both forms (base and this).
14The example corresponds to the code shown below, where each comment indicates an automatically inserted
15statement (the syntax used for the automatically inserted constructor invocations isn’t valid, but merely
16serves to illustrate the mechanism).
17using System.Collections;
18class A
19{
20 |
int x, |
y, count; |
|
21 |
public |
A() { |
|
22 |
x = |
1; |
// Variable initializer |
23 |
y = -1; |
// Variable initializer |
|
24 |
object(); |
// Invoke object() constructor |
|
25 |
count = 0; |
|
|
26 |
} |
|
|
27 |
public A(int n) { |
|
|
28 |
x = 1; |
// Variable initializer |
|
29 |
y = -1; |
// Variable initializer |
|
30 |
object(); |
// Invoke object() constructor |
|
31 |
count = n; |
|
32}
33}
34class B: A
35{
36 |
double sqrt2; |
|
|
37 |
ArrayList items; |
|
|
38 |
int max; |
|
|
39 |
public B(): this(100) { |
|
|
40 |
B(100); |
// Invoke B(int) constructor |
|
41 |
items.Add("default"); |
|
|
42 |
} |
|
|
43 |
public B(int n): base(n – 1) { |
|
|
44 |
sqrt2 |
= Math.Sqrt(2.0); |
// Variable initializer |
45 |
items |
= new ArrayList(100); |
// Variable initializer |
46 |
A(n – |
1); |
// Invoke A(int) constructor |
47 |
max = |
n; |
|
48}
49}
50end example]
5117.10.4 Default constructors
52If a class contains no instance constructor declarations, a default instance constructor is automatically
53provided. That default constructor simply invokes the parameterless constructor of the direct base class. If
54the direct base class does not have an accessible parameterless instance constructor, a compile-time error
55occurs. If the class is abstract then the declared accessibility for the default constructor is protected.
56Otherwise, the declared accessibility for the default constructor is public. [Note: Thus, the default
57constructor is always of the form
314