
- •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 |
||
|
|
|
|
checked and unchecked |
static void Main() { |
|
|
statements |
int x = Int32.MaxValue; |
|
|
Console.WriteLine(x + 1); |
// Overflow |
||
|
|||
|
checked { |
|
|
|
Console.WriteLine(x + 1); |
// Exception |
|
|
} |
|
|
|
unchecked { |
|
|
|
Console.WriteLine(x + 1); |
// Overflow |
|
|
} |
|
|
|
} |
|
|
|
|
|
|
lock statements |
static void Main() { |
|
|
|
A a = …; |
|
|
|
lock(a) { |
|
|
|
a.P = a.P + 1; |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
using statements |
static void Main() { |
|
|
|
using (Resource r = new Resource()) { |
||
|
r.F(); |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
1
28.7 Classes
3Class declarations define new reference types. A class can inherit from another class, and can implement
4interfaces. Generic class declarations (§26.1) have one or more type parameters.
5Class members can include constants, fields, methods, properties, events, indexers, operators, instance
6constructors, destructors, static constructors, and nested type declarations. Each member has an associated
7accessibility (§10.5), which controls the regions of program text that are able to access the member. There
8are five possible forms of accessibility. These are summarized in the table below.
9
Form |
Intuitive meaning |
|
|
public |
Access not limited |
|
|
protected |
Access limited to the containing class or types derived from the containing class |
|
|
internal |
Access limited to this program |
|
|
protected |
Access limited to this program or types derived from the containing class |
internal |
|
private |
Access limited to the containing type |
|
|
10
11The example
12using System;
13class MyClass
14{
15 |
public |
const int MyConst = 12; |
16 |
public |
int MyField = 34; |
17 |
public |
static int MyStaticField = 34; |
18 |
public void MyMethod(){ |
|
19 |
Console.WriteLine("MyClass.MyMethod"); |
|
20 |
} |
|
21 |
public int MyProperty { |
|
22 |
get { |
|
23 |
return MyField; |
|
24 |
} |
|
31
|
C# LANGUAGE SPECIFICATION |
1 |
set { |
2 |
MyField = value; |
3 |
} |
4 |
} |
5 |
public event EventHandler MyEvent; |
6 |
public int this[int index] { |
7 |
get { |
8 |
return 0; |
9 |
} |
10 |
set { |
11 |
Console.WriteLine("this[{0}] = {1}", index, value); |
12 |
} |
13 |
} |
14 |
public static MyClass operator+(MyClass a, MyClass b) { |
15 |
return new MyClass(a.MyField + b.MyField); |
16 |
} |
17 |
public MyClass() { |
18 |
Console.WriteLine("Instance constructor"); |
19 |
} |
20 |
public MyClass(int value) { |
21 |
MyField = value; |
22 |
Console.WriteLine("Instance constructor"); |
23 |
} |
24 |
~MyClass() { |
25 |
Console.WriteLine("Destructor"); |
26 |
} |
27 |
static MyClass() { |
28 |
MyStaticField *= 2; |
29 |
Console.WriteLine("Static constructor"); |
30 |
} |
31 |
internal class MyNestedClass |
32{}
33}
34shows a class that contains each kind of member. The example
35class Test
36{
37 |
static void Main() { |
38 |
// Instance constructor usage |
39 |
MyClass a = new MyClass(); |
40 |
MyClass b = new MyClass(123); |
41 |
// Constant usage |
42 |
Console.WriteLine("MyConst = {0}", MyClass.MyConst); |
43 |
// Field usage |
44 |
a.MyField++; |
45 |
Console.WriteLine("a.MyField = {0}", a.MyField); |
46 |
// Method usage |
47 |
a.MyMethod(); |
48 |
// Property usage |
49 |
a.MyProperty++; |
50 |
Console.WriteLine("a.MyProperty = {0}", a.MyProperty); |
51 |
// Indexer usage |
52 |
a[3] = a[1] = a[2]; |
53 |
Console.WriteLine("a[3] = {0}", a[3]); |
54 |
// Event usage |
55 |
a.MyEvent += new EventHandler(MyHandler); |
56 |
// Overloaded operator usage |
57 |
MyClass c = a + b; |
32
|
Chapter 8 Language overview |
1 |
// Nested type usage |
2 |
MyClass.MyNestedClass d = new MyClass.MyNestedClass(); |
3 |
} |
4 |
static void MyHandler(object sender, EventArgs e) { |
5 |
Console.WriteLine("Test.MyHandler"); |
6}
7}
8shows uses of these members.
98.7.1 Constants
10A constant is a class member that represents a constant value: a value that can be computed at compile-time.
11Constants are permitted to depend on other constants within the same program as long as there are no
12circular dependencies. The rules governing constant expressions are defined in §14.15. The example
13class Constants
14{
15 |
public const int A = 1; |
16public const int B = A + 1;
17}
18shows a class named Constants that has two public constants.
19Even though constants are considered static members, a constant declaration neither requires nor allows the
20modifier static. Constants can be accessed through the class, as in
21using System;
22class Test
23{
24 |
static void Main() { |
25 |
Console.WriteLine("{0}, {1}", Constants.A, Constants.B); |
26}
27}
28which prints out the values of Constants.A and Constants.B, respectively.
298.7.2 Fields
30A field is a member that represents a variable associated with an object or class. The example
31class Color
32{
33 |
internal ushort redPart; |
34 |
internal ushort bluePart; |
35 |
internal ushort greenPart; |
36 |
public Color(ushort red, ushort blue, ushort green) { |
37 |
redPart = red; |
38 |
bluePart = blue; |
39 |
greenPart = green; |
40 |
} |
41 |
public static Color Red = new Color(0xFF, 0, 0); |
42 |
public static Color Blue = new Color(0, 0xFF, 0); |
43 |
public static Color Green = new Color(0, 0, 0xFF); |
44public static Color White = new Color(0xFF, 0xFF, 0xFF);
45}
46shows a Color class that has internal instance fields named redPart, bluePart, and greenPart, and
47static fields named Red, Blue, Green, and White
48The use of static fields in this manner is not ideal. The fields are initialized at some point before they are
49used, but after this initialization there is nothing to stop a client from changing them. Such a modification
50could cause unpredictable errors in other programs that use Color and assume that the values do not
51change. Readonly fields can be used to prevent such problems. Assignments to a readonly field can only
52occur as part of the declaration, or in an instance constructor or static constructor in the same class. A static
53readonly field can be assigned in a static constructor, and a non-static readonly field can be assigned in an
33
C# LANGUAGE SPECIFICATION
1instance constructor. Thus, the Color class can be enhanced by adding the modifier readonly to the static
2fields:
3class Color
4{
5 |
internal ushort redPart; |
6 |
internal ushort bluePart; |
7 |
internal ushort greenPart; |
8 |
public Color(ushort red, ushort blue, ushort green) { |
9 |
redPart = red; |
10 |
bluePart = blue; |
11 |
greenPart = green; |
12 |
} |
13 |
public static readonly Color Red = new Color(0xFF, 0, 0); |
14 |
public static readonly Color Blue = new Color(0, 0xFF, 0); |
15 |
public static readonly Color Green = new Color(0, 0, 0xFF); |
16public static readonly Color White = new Color(0xFF, 0xFF, 0xFF);
17}
188.7.3 Methods
19A method is a member that implements a computation or action that can be performed by an object or class.
20Methods have a (possibly empty) list of formal parameters, a return value (unless the method’s return-type is
21void), and are either static or non-static. Static methods are accessed through the class. Non-static methods,
22which are also called instance methods, are accessed through instances of the class. A generic method
23(§26.6) has a list of one or more type parameters. The example
24using System;
25public class Stack
26{
27 |
public static Stack Clone(Stack s) {…} |
28 |
public static Stack Flip(Stack s) {…} |
29 |
public object Pop() {…} |
30 |
public void Push(object o) {…} |
31 |
public void PushMultiple<T>(T[] a) {…} |
32 |
public override string ToString() {…} |
33…
34}
35class Test
36{
37 |
static void Main() { |
38 |
Stack s = new Stack(); |
39 |
for (int i = 1; i < 10; i++) |
40 |
s.Push(i); |
41 |
Stack flipped = Stack.Flip(s); |
42 |
Stack cloned = Stack.Clone(s); |
43 |
Console.WriteLine("Original stack: " + s.ToString()); |
44 |
Console.WriteLine("Flipped stack: " + flipped.ToString()); |
45 |
Console.WriteLine("Cloned stack: " + cloned.ToString()); |
46}
47}
48shows a Stack that has several static methods (Clone and Flip) and several instance methods (Pop, Push,
49and ToString) and a generic method (PushMultiple<T>).
50Methods can be overloaded, which means that multiple methods can have the same name so long as they
51have unique signatures. The signature of a method consists of the name of the method and the number,
52modifiers, and types of its formal parameters, and the number of generic type parameters. The signature of a
53method does not include the return type or the names of the formal parameters or type parameters. The
54example
34