
- •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
1using System;
2class Test
3{
4 |
static void F() { |
5 |
Console.WriteLine("F()"); |
6 |
} |
7 |
static void F(object o) { |
8 |
Console.WriteLine("F(object)"); |
9 |
} |
10 |
static void F(int value) { |
11 |
Console.WriteLine("F(int)"); |
12 |
} |
13 |
static void F(ref int value) { |
14 |
Console.WriteLine("F(ref int)"); |
15 |
} |
16 |
static void F(int a, int b) { |
17 |
Console.WriteLine("F(int, int)"); |
18 |
} |
19 |
static void F(int[] values) { |
20 |
Console.WriteLine("F(int[])"); |
21 |
} |
22 |
static void F<T>(T t) { |
23 |
Console.WriteLine("F<T>(T)"); |
24 |
} |
25 |
static void Main() { |
26 |
F(); |
27 |
F(1); |
28 |
int i = 10; |
29 |
F(ref i); |
30 |
F((object)1); |
31 |
F(1, 2); |
32 |
F(new int[] {1, 2, 3}); |
33 |
F("Hello"); |
34 |
F<string>("World"); |
35}
36}
37shows a class with a number of methods called F. The output produced is
38F()
39F(int)
40F(ref int)
41F(object)
42F(int, int)
43F(int[])
44F<T>(T)
45F<T>(T)
468.7.4 Properties
47A property is a member that provides access to a characteristic of an object or a class. Examples of
48properties include the length of a string, the size of a font, the caption of a window, the name of a customer,
49and so on. Properties are a natural extension of fields. Both are named members with associated types, and
50the syntax for accessing fields and properties is the same. However, unlike fields, properties do not denote
51storage locations. Instead, properties have accessors that specify the statements to be executed when their
52values are read or written.
53Properties are defined with property declarations. The first part of a property declaration looks quite similar
54to a field declaration. The second part includes a get accessor and/or a set accessor. In the example below,
55the Button class defines a Caption property.
35
C# LANGUAGE SPECIFICATION
1public class Button
2{
3 |
private string caption; |
4 |
public string Caption { |
5 |
get { |
6 |
return caption; |
7 |
} |
8 |
set { |
9 |
caption = value; |
10 |
Repaint(); |
11 |
} |
12 |
} |
13…
14}
15Properties that can be both read and written, such as Caption, include both get and set accessors. The get
16accessor is called when the property’s value is read; the set accessor is called when the property’s value is
17written. In a set accessor, the new value for the property is made available via an implicit parameter named
18value.
19The declaration of properties is relatively straightforward, but the real value of properties is seen when they
20are used. For example, the Caption property can be read and written in the same way that fields can be read
21and written:
22Button b = new Button();
23 |
b.Caption = "ABC"; |
// set; causes repaint |
24 |
string s = b.Caption; |
// get |
25 |
b.Caption += "DEF"; |
// get & set; causes repaint |
268.7.5 Events
27An event is a member that enables an object or class to provide notifications. A class defines an event by
28providing an event declaration (which resembles a field declaration, though with an added event keyword)
29and an optional set of event accessors. The type of this declaration shall be a delegate type.
30An instance of a delegate type encapsulates one or more callable entities. For instance methods, a callable
31entity consists of an instance and a method on that instance. For static methods, a callable entity consists of
32just a method. Given a delegate instance and an appropriate set of arguments, one can invoke all of that
33delegate instance’s methods with that set of arguments.
34In the example
35public delegate void EventHandler(object sender, System.EventArgs e);
36public class Button
37{
38 |
public event EventHandler Click; |
39 |
public void Reset() { |
40 |
Click = null; |
41}
42}
43the Button class defines a Click event of type EventHandler. Inside the Button class, the Click
44member is exactly like a private field of type EventHandler. However, outside the Button class, the
45Click member can only be used on the left-hand side of the += and –= operators. The += operator adds a
46handler for the event, and the -= operator removes a handler for the event. The example
47using System;
48public class Form1
49{
50 |
public Form1() { |
51 |
// Add Button1_Click as an event handler for Button1’s Click event |
52 |
Button1.Click += new EventHandler(Button1_Click); |
53 |
} |
54 |
Button Button1 = new Button(); |
36
|
Chapter 8 Language overview |
1 |
void Button1_Click(object sender, EventArgs e) { |
2 |
Console.WriteLine("Button1 was clicked!"); |
3 |
} |
4 |
public void Disconnect() { |
5 |
Button1.Click -= new EventHandler(Button1_Click); |
6}
7}
8shows a Form1 class that adds Button1_Click as an event handler for Button1’s Click event. In the
9Disconnect method, that event handler is removed.
10For a simple event declaration such as
11public event EventHandler Click;
12the compiler automatically provides the implementation underlying the += and -= operators.
13An implementer who wants more control can get it by explicitly providing add and remove accessors. For
14example, the Button class could be rewritten as follows:
15public class Button
16{
17 |
private EventHandler handler; |
18 |
public event EventHandler Click { |
19 |
add { handler += value; } |
20 |
|
21 |
remove { handler -= value; } |
22 |
} |
23}
24This change has no effect on client code, but allows the Button class more implementation flexibility. For
25example, the event handler for Click need not be represented by a field.
268.7.6 Operators
27An operator is a member that defines the meaning of an expression operator that can be applied to instances
28of the class. There are three kinds of operators that can be defined: unary operators, binary operators, and
29conversion operators.
30The following example defines a Digit type that represents decimal digits—integral values between 0
31and 9.
32using System;
33public struct Digit
34{
35 |
byte value; |
36 |
public Digit(int value) { |
37 |
if (value < 0 || value > 9) throw new ArgumentException(); |
38 |
this.value = (byte)value; |
39 |
} |
40 |
public static implicit operator byte(Digit d) { |
41 |
return d.value; |
42 |
} |
43 |
public static explicit operator Digit(int value) { |
44 |
return new Digit(value); |
45 |
} |
46 |
public static Digit operator+(Digit a, Digit b) { |
47 |
return new Digit(a.value + b.value); |
48 |
} |
49 |
public static Digit operator-(Digit a, Digit b) { |
50 |
return new Digit(a.value - b.value); |
51 |
} |
37
|
C# LANGUAGE SPECIFICATION |
1 |
public static bool operator==(Digit a, Digit b) { |
2 |
return a.value == b.value; |
3 |
} |
4 |
public static bool operator!=(Digit a, Digit b) { |
5 |
return a.value != b.value; |
6 |
} |
7 |
public override bool Equals(object value) { |
8 |
if (value == null) return false; |
9 |
if (GetType() == value.GetType()) return this == (Digit)value; |
10 |
return false; |
11 |
} |
12 |
public override int GetHashCode() { |
13 |
return value.GetHashCode(); |
14 |
} |
15 |
public override string ToString() { |
16 |
return value.ToString(); |
17}
18}
19class Test
20{
21 |
static void Main() { |
22 |
Digit a = (Digit) 5; |
23 |
Digit b = (Digit) 3; |
24 |
Digit plus = a + b; |
25 |
Digit minus = a - b; |
26 |
bool equals = (a == b); |
27 |
Console.WriteLine("{0} + {1} = {2}", a, b, plus); |
28 |
Console.WriteLine("{0} - {1} = {2}", a, b, minus); |
29 |
Console.WriteLine("{0} == {1} = {2}", a, b, equals); |
30}
31}
32The Digit type defines the following operators:
33• An implicit conversion operator from Digit to byte.
34• An explicit conversion operator from int to Digit.
35• An addition operator that adds two Digit values and returns a Digit value.
36• A subtraction operator that subtracts one Digit value from another, and returns a Digit value.
37• The equality (==) and inequality (!=) operators, which compare two Digit values.
388.7.7 Indexers
39An indexer is a member that enables an object to be indexed in the same way as an array. Whereas
40properties enable field-like access, indexers enable array-like access.
41As an example, consider the Stack class presented earlier. The designer of this class might want to expose
42array-like access so that it is possible to inspect or alter the items on the stack without performing
43unnecessary Push and Pop operations. That is, class Stack is implemented as a linked list, but it also
44provides the convenience of array access.
45Indexer declarations are similar to property declarations, with the main differences being that indexers are
46nameless (the “name” used in the declaration is this, since this is being indexed) and that indexers
47include indexing parameters. The indexing parameters are provided between square brackets. The example
48using System;
38