
- •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 8 Language overview
1public class Stack
2{
3 |
private Node GetNode(int index) { |
4 |
Node temp = first; |
5 |
while (true) { |
6 |
if (temp == null || index < 0) |
7 |
throw new Exception("Index out of range."); |
8 |
if (index == 0) |
9 |
return temp; |
10 |
temp = temp.Next; |
11 |
index--; |
12 |
} |
13 |
} |
14 |
public object this[int index] { |
15 |
get { |
16 |
return GetNode(index).Value; |
17 |
} |
18 |
set { |
19 |
GetNode(index).Value = value; |
20 |
} |
21 |
} |
22…
23}
24class Test
25{
26 |
static void Main() { |
|
|
27 |
Stack s = new Stack(); |
|
|
28 |
s.Push(1); |
|
|
29 |
s.Push(2); |
|
|
30 |
s.Push(3); |
|
|
31 |
s[0] = 33; |
// Changes the top item from 3 to 33 |
|
32 |
s[1] = 22; |
// Changes the middle item from 2 |
to 22 |
33 |
s[2] = 11; |
// Changes the bottom item from 1 |
to 11 |
34}
35}
36shows an indexer for the Stack class.
378.7.8 Instance constructors
38An instance constructor is a member that implements the actions required to initialize an instance of a class.
39The example
40using System;
41class Point
42{
43 |
public double x, y; |
44 |
public Point() { |
45 |
this.x = 0; |
46 |
this.y = 0; |
47 |
} |
48 |
public Point(double x, double y) { |
49 |
this.x = x; |
50 |
this.y = y; |
51 |
} |
52 |
public static double Distance(Point a, Point b) { |
53 |
double xdiff = a.x - b.x; |
54 |
double ydiff = a.y - b.y; |
55 |
return Math.Sqrt(xdiff * xdiff + ydiff * ydiff); |
56 |
} |
39
|
C# LANGUAGE SPECIFICATION |
1 |
public override string ToString() { |
2 |
return string.Format("({0}, {1})", x, y); |
3}
4}
5class Test
6{
7 |
static void Main() { |
8 |
Point a = new Point(); |
9 |
Point b = new Point(3, 4); |
10 |
double d = Point.Distance(a, b); |
11 |
Console.WriteLine("Distance from {0} to {1} is {2}", a, b, d); |
12}
13}
14shows a Point class that provides two public instance constructors, one of which takes no arguments, while
15the other takes two double arguments.
16If no instance constructor is supplied for a class, then one having no parameters is automatically provided,
17which simply invokes the parameterless constructor of the direct base class.
188.7.9 Destructors
19A destructor is a member that implements the actions required to destruct an instance of a class. Destructors
20cannot have parameters, they cannot have accessibility modifiers, and they cannot be called explicitly. The
21destructor for an instance is called automatically during garbage collection.
22The example
23using System;
24class Point
25{
26 |
public double x, y; |
27 |
public Point(double x, double y) { |
28 |
this.x = x; |
29 |
this.y = y; |
30 |
} |
31 |
~Point() { |
32 |
Console.WriteLine("Destructed {0}", this); |
33 |
} |
34 |
public override string ToString() { |
35 |
return string.Format("({0}, {1})", x, y); |
36}
37}
38shows a Point class with a destructor.
398.7.10 Static constructors
40A static constructor is a member that implements the actions required to initialize a class. Static constructors
41cannot have parameters, they cannot have accessibility modifiers, and they cannot be called explicitly. The
42static constructor for a class is called automatically.
43The example
44using Personnel.Data;
45class Employee
46{
47 |
private static DataSet ds; |
48 |
static Employee() { |
49 |
ds = new DataSet(…); |
50 |
} |
40
Chapter 8 Language overview
1 |
public |
string Name; |
2 |
public |
decimal Salary; |
3…
4}
5shows an Employee class with a static constructor that initializes a static field.
68.7.11 Inheritance
7Classes support single inheritance, and the type object is the ultimate base class for all classes.
8The classes shown in earlier examples all implicitly derive from object. The example
9using System;
10class A
11{
12public void F() { Console.WriteLine("A.F"); }
13}
14shows a class A that implicitly derives from object. The example
15class B: A
16{
17public void G() { Console.WriteLine("B.G"); }
18}
19class Test
20{
21 |
static void Main() { |
|
22 |
B b = new B(); |
|
23 |
b.F(); |
// Inherited from A |
24 |
b.G(); |
// Introduced in B |
25 |
|
|
26 |
A a = b; |
// Treat a B as an A |
27 |
a.F(); |
|
28}
29}
30shows a class B that derives from A. The class B inherits A’s F method, and introduces a G method of its own.
31Methods, properties, and indexers can be virtual, which means that their implementation can be overridden
32in derived classes. The example
33using System;
34class A
35{
36public virtual void F() { Console.WriteLine("A.F"); }
37}
38class B: A
39{
40 |
public override void F() { |
41 |
base.F(); |
42 |
Console.WriteLine("B.F"); |
43}
44}
45class Test
46{
47 |
static void Main() { |
48 |
B b = new B(); |
49 |
b.F(); |
50 |
A a = b; |
51 |
a.F(); |
52}
53}
54shows a class A with a virtual method F, and a class B that overrides F. The overriding method in B contains
55a call, base.F(), which calls the overridden method in A.
41
C# LANGUAGE SPECIFICATION
1A class can indicate that it is incomplete, and is intended only as a base class for other classes, by including
2the modifier abstract. Such a class is called an abstract class. An abstract class can specify abstract
3members—members that a non-abstract derived class shall implement. The example
4using System;
5abstract class A
6{
7public abstract void F();
8}
9class B: A
10{
11public override void F() { Console.WriteLine("B.F"); }
12}
13class Test
14{
15 |
static void Main() { |
16 |
B b = new B(); |
17 |
b.F(); |
18 |
A a = b; |
19 |
a.F(); |
20}
21}
22introduces an abstract method F in the abstract class A. The non-abstract class B provides an implementation
23for this method.
248.7.12 Static classes
25Classes that are not intended to be instantiated, and which contain only static members should be declared as
26static classes. Examples of such classes are System.Console and System.Environment. Static classes
27are implicitly sealed and have no instance constructors. Static classes can be used only with the typeof
28operator and to access elements of the class. In particular, a static class cannot be used as the type of a
29variable or be used as a type argument.
30public static class Months
31{
32 |
static Months() { … } |
33 |
private static readonly string[] monthName = { … } |
34 |
public static string GetMonthName(int mm) { … } |
35 |
private static readonly int[,] daysInMonth = { … } |
36 |
public static int GetDaysInMonth(bool isLeapYear, int mm) { … } |
37public static bool IsLeapYear(int yy) { … }
38}
398.7.13 Partial type declarations
40In certain situations, the declaration of a type may grow so large that keeping it in a single source file
41becomes impractical or difficult. In such cases, it is often desirable to split that class declaration into
42multiple source files, with each source file focussing on one or more semi-independent concerns.
43Another common situation occurs when code is generated from a program rather than written by a person. In
44rich frameworks and development environments, it is often most efficient to have parts of a project’s source
45code generated automatically from visual form designers, database schemas, RPC descriptions, etc. While
46these kinds of tools produce huge productivity gains, they suffer from problems when we wish to customize
47the output, possibly by adding members to generated classes. If we directly modify the output of the code
48generator, then those changes will be lost if the code generator needs to be run again. By placing the
49customized additions in a different source file, lost modifications can be greatly reduced or eliminated.
50Partial type declarations allow greater flexibility in these situations by allowing the definition of a class,
51struct, or interface to be split into as many different pieces as needed. For example, when the following
52source files are compiled together:
42