
- •Foreword
- •Introduction
- •Scope
- •Conformance
- •Normative references
- •Definitions
- •Notational conventions
- •Acronyms and abbreviations
- •General description
- •Language overview
- •Getting started
- •Types
- •Predefined types
- •Conversions
- •Array types
- •Type system unification
- •Variables and parameters
- •Automatic memory management
- •Expressions
- •Statements
- •Classes
- •Constants
- •Fields
- •Methods
- •Properties
- •Events
- •Operators
- •Indexers
- •Instance constructors
- •Destructors
- •Static constructors
- •Inheritance
- •Static classes
- •Partial type declarations
- •Structs
- •Interfaces
- •Delegates
- •Enums
- •Namespaces and assemblies
- •Versioning
- •Extern Aliases
- •Attributes
- •Generics
- •Why generics?
- •Creating and consuming generics
- •Multiple type parameters
- •Constraints
- •Generic methods
- •Anonymous methods
- •Iterators
- •Lexical structure
- •Programs
- •Grammars
- •Lexical grammar
- •Syntactic grammar
- •Grammar ambiguities
- •Lexical analysis
- •Line terminators
- •Comments
- •White space
- •Tokens
- •Unicode escape sequences
- •Identifiers
- •Keywords
- •Literals
- •Boolean literals
- •Integer literals
- •Real literals
- •Character literals
- •String literals
- •The null literal
- •Operators and punctuators
- •Pre-processing directives
- •Conditional compilation symbols
- •Pre-processing expressions
- •Declaration directives
- •Conditional compilation directives
- •Diagnostic directives
- •Region control
- •Line directives
- •Pragma directives
- •Basic concepts
- •Application startup
- •Application termination
- •Declarations
- •Members
- •Namespace members
- •Struct members
- •Enumeration members
- •Class members
- •Interface members
- •Array members
- •Delegate members
- •Member access
- •Declared accessibility
- •Accessibility domains
- •Protected access for instance members
- •Accessibility constraints
- •Signatures and overloading
- •Scopes
- •Name hiding
- •Hiding through nesting
- •Hiding through inheritance
- •Namespace and type names
- •Unqualified name
- •Fully qualified names
- •Automatic memory management
- •Execution order
- •Types
- •Value types
- •The System.ValueType type
- •Default constructors
- •Struct types
- •Simple types
- •Integral types
- •Floating point types
- •The decimal type
- •The bool type
- •Enumeration types
- •Reference types
- •Class types
- •The object type
- •The string type
- •Interface types
- •Array types
- •Delegate types
- •Boxing and unboxing
- •Boxing conversions
- •Unboxing conversions
- •Variables
- •Variable categories
- •Static variables
- •Instance variables
- •Instance variables in classes
- •Instance variables in structs
- •Array elements
- •Value parameters
- •Reference parameters
- •Output parameters
- •Local variables
- •Default values
- •Definite assignment
- •Initially assigned variables
- •Initially unassigned variables
- •Precise rules for determining definite assignment
- •General rules for statements
- •Block statements, checked, and unchecked statements
- •Expression statements
- •Declaration statements
- •If statements
- •Switch statements
- •While statements
- •Do statements
- •For statements
- •Break, continue, and goto statements
- •Throw statements
- •Return statements
- •Try-catch statements
- •Try-finally statements
- •Try-catch-finally statements
- •Foreach statements
- •Using statements
- •Lock statements
- •General rules for simple expressions
- •General rules for expressions with embedded expressions
- •Invocation expressions and object creation expressions
- •Simple assignment expressions
- •&& expressions
- •|| expressions
- •! expressions
- •?: expressions
- •Anonymous method expressions
- •Yield statements
- •Variable references
- •Atomicity of variable references
- •Conversions
- •Implicit conversions
- •Identity conversion
- •Implicit numeric conversions
- •Implicit enumeration conversions
- •Implicit reference conversions
- •Boxing conversions
- •Implicit type parameter conversions
- •Implicit constant expression conversions
- •User-defined implicit conversions
- •Explicit conversions
- •Explicit numeric conversions
- •Explicit enumeration conversions
- •Explicit reference conversions
- •Unboxing conversions
- •User-defined explicit conversions
- •Standard conversions
- •Standard implicit conversions
- •Standard explicit conversions
- •User-defined conversions
- •Permitted user-defined conversions
- •Evaluation of user-defined conversions
- •User-defined implicit conversions
- •User-defined explicit conversions
- •Anonymous method conversions
- •Method group conversions
- •Expressions
- •Expression classifications
- •Values of expressions
- •Operators
- •Operator precedence and associativity
- •Operator overloading
- •Unary operator overload resolution
- •Binary operator overload resolution
- •Candidate user-defined operators
- •Numeric promotions
- •Unary numeric promotions
- •Binary numeric promotions
- •Member lookup
- •Base types
- •Function members
- •Argument lists
- •Overload resolution
- •Applicable function member
- •Better function member
- •Better conversion
- •Function member invocation
- •Invocations on boxed instances
- •Primary expressions
- •Literals
- •Simple names
- •Invariant meaning in blocks
- •Parenthesized expressions
- •Member access
- •Identical simple names and type names
- •Invocation expressions
- •Method invocations
- •Delegate invocations
- •Element access
- •Array access
- •Indexer access
- •This access
- •Base access
- •Postfix increment and decrement operators
- •The new operator
- •Object creation expressions
- •Array creation expressions
- •Delegate creation expressions
- •The typeof operator
- •The checked and unchecked operators
- •Default value expression
- •Anonymous methods
- •Anonymous method signatures
- •Anonymous method blocks
- •Outer variables
- •Captured outer variables
- •Instantiation of local variables
- •Anonymous method evaluation
- •Implementation example
- •Unary expressions
- •Unary plus operator
- •Unary minus operator
- •Logical negation operator
- •Bitwise complement operator
- •Prefix increment and decrement operators
- •Cast expressions
- •Arithmetic operators
- •Multiplication operator
- •Division operator
- •Remainder operator
- •Addition operator
- •Subtraction operator
- •Shift operators
- •Relational and type-testing operators
- •Integer comparison operators
- •Floating-point comparison operators
- •Decimal comparison operators
- •Boolean equality operators
- •Enumeration comparison operators
- •Reference type equality operators
- •String equality operators
- •Delegate equality operators
- •The is operator
- •The as operator
- •Logical operators
- •Integer logical operators
- •Enumeration logical operators
- •Boolean logical operators
- •Conditional logical operators
- •Boolean conditional logical operators
- •User-defined conditional logical operators
- •Conditional operator
- •Assignment operators
- •Simple assignment
- •Compound assignment
- •Event assignment
- •Expression
- •Constant expressions
- •Boolean expressions
- •Statements
- •End points and reachability
- •Blocks
- •Statement lists
- •The empty statement
- •Labeled statements
- •Declaration statements
- •Local variable declarations
- •Local constant declarations
- •Expression statements
- •Selection statements
- •The if statement
- •The switch statement
- •Iteration statements
- •The while statement
- •The do statement
- •The for statement
- •The foreach statement
- •Jump statements
- •The break statement
- •The continue statement
- •The goto statement
- •The return statement
- •The throw statement
- •The try statement
- •The checked and unchecked statements
- •The lock statement
- •The using statement
- •The yield statement
- •Namespaces
- •Compilation units
- •Namespace declarations
- •Extern alias directives
- •Using directives
- •Using alias directives
- •Using namespace directives
- •Namespace members
- •Type declarations
- •Qualified alias member
- •Classes
- •Class declarations
- •Class modifiers
- •Abstract classes
- •Sealed classes
- •Static classes
- •Class base specification
- •Base classes
- •Interface implementations
- •Class body
- •Partial declarations
- •Class members
- •Inheritance
- •The new modifier
- •Access modifiers
- •Constituent types
- •Static and instance members
- •Nested types
- •Fully qualified name
- •Declared accessibility
- •Hiding
- •this access
- •Reserved member names
- •Member names reserved for properties
- •Member names reserved for events
- •Member names reserved for indexers
- •Member names reserved for destructors
- •Constants
- •Fields
- •Static and instance fields
- •Readonly fields
- •Using static readonly fields for constants
- •Versioning of constants and static readonly fields
- •Volatile fields
- •Field initialization
- •Variable initializers
- •Static field initialization
- •Instance field initialization
- •Methods
- •Method parameters
- •Value parameters
- •Reference parameters
- •Output parameters
- •Parameter arrays
- •Static and instance methods
- •Virtual methods
- •Override methods
- •Sealed methods
- •Abstract methods
- •External methods
- •Method body
- •Method overloading
- •Properties
- •Static and instance properties
- •Accessors
- •Virtual, sealed, override, and abstract accessors
- •Events
- •Field-like events
- •Event accessors
- •Static and instance events
- •Virtual, sealed, override, and abstract accessors
- •Indexers
- •Indexer overloading
- •Operators
- •Unary operators
- •Binary operators
- •Conversion operators
- •Instance constructors
- •Constructor initializers
- •Instance variable initializers
- •Constructor execution
- •Default constructors
- •Private constructors
- •Optional instance constructor parameters
- •Static constructors
- •Destructors
- •Structs
- •Struct declarations
- •Struct modifiers
- •Struct interfaces
- •Struct body
- •Struct members
- •Class and struct differences
- •Value semantics
- •Inheritance
- •Assignment
- •Default values
- •Boxing and unboxing
- •Meaning of this
- •Field initializers
- •Constructors
- •Destructors
- •Static constructors
- •Struct examples
- •Database integer type
- •Database boolean type
- •Arrays
- •Array types
- •The System.Array type
- •Array creation
- •Array element access
- •Array members
- •Array covariance
- •Arrays and the generic IList interface
- •Array initializers
- •Interfaces
- •Interface declarations
- •Interface modifiers
- •Base interfaces
- •Interface body
- •Interface members
- •Interface methods
- •Interface properties
- •Interface events
- •Interface indexers
- •Interface member access
- •Fully qualified interface member names
- •Interface implementations
- •Explicit interface member implementations
- •Interface mapping
- •Interface implementation inheritance
- •Interface re-implementation
- •Abstract classes and interfaces
- •Enums
- •Enum declarations
- •Enum modifiers
- •Enum members
- •The System.Enum type
- •Enum values and operations
- •Delegates
- •Delegate declarations
- •Delegate instantiation
- •Delegate invocation
- •Exceptions
- •Causes of exceptions
- •The System.Exception class
- •How exceptions are handled
- •Common Exception Classes
- •Attributes
- •Attribute classes
- •Attribute usage
- •Positional and named parameters
- •Attribute parameter types
- •Attribute specification
- •Attribute instances
- •Compilation of an attribute
- •Run-time retrieval of an attribute instance
- •Reserved attributes
- •The AttributeUsage attribute
- •The Conditional attribute
- •Conditional Methods
- •Conditional Attribute Classes
- •The Obsolete attribute
- •Unsafe code
- •Unsafe contexts
- •Pointer types
- •Fixed and moveable variables
- •Pointer conversions
- •Pointers in expressions
- •Pointer indirection
- •Pointer member access
- •Pointer element access
- •The address-of operator
- •Pointer increment and decrement
- •Pointer arithmetic
- •Pointer comparison
- •The sizeof operator
- •The fixed statement
- •Stack allocation
- •Dynamic memory allocation
- •Generics
- •Generic class declarations
- •Type parameters
- •The instance type
- •Members of generic classes
- •Static fields in generic classes
- •Static constructors in generic classes
- •Accessing protected members
- •Overloading in generic classes
- •Parameter array methods and type parameters
- •Overriding and generic classes
- •Operators in generic classes
- •Nested types in generic classes
- •Generic struct declarations
- •Generic interface declarations
- •Uniqueness of implemented interfaces
- •Explicit interface member implementations
- •Generic delegate declarations
- •Constructed types
- •Type arguments
- •Open and closed types
- •Base classes and interfaces of a constructed type
- •Members of a constructed type
- •Accessibility of a constructed type
- •Conversions
- •Using alias directives
- •Generic methods
- •Generic method signatures
- •Virtual generic methods
- •Calling generic methods
- •Inference of type arguments
- •Using a generic method with a delegate
- •Constraints
- •Satisfying constraints
- •Member lookup on type parameters
- •Type parameters and boxing
- •Conversions involving type parameters
- •Iterators
- •Iterator blocks
- •Enumerator interfaces
- •Enumerable interfaces
- •Yield type
- •This access
- •Enumerator objects
- •The MoveNext method
- •The Current property
- •The Dispose method
- •Enumerable objects
- •The GetEnumerator method
- •Implementation example
- •Lexical grammar
- •Line terminators
- •White space
- •Comments
- •Unicode character escape sequences
- •Identifiers
- •Keywords
- •Literals
- •Operators and punctuators
- •Pre-processing directives
- •Syntactic grammar
- •Basic concepts
- •Types
- •Expressions
- •Statements
- •Classes
- •Structs
- •Arrays
- •Interfaces
- •Enums
- •Delegates
- •Attributes
- •Generics
- •Grammar extensions for unsafe code
- •Undefined behavior
- •Implementation-defined behavior
- •Unspecified behavior
- •Other Issues
- •Capitalization styles
- •Pascal casing
- •Camel casing
- •All uppercase
- •Capitalization summary
- •Word choice
- •Namespaces
- •Classes
- •Interfaces
- •Enums
- •Static fields
- •Parameters
- •Methods
- •Properties
- •Events
- •Case sensitivity
- •Avoiding type name confusion
- •Documentation Comments
- •Introduction
- •Recommended tags
- •<code>
- •<example>
- •<exception>
- •<list>
- •<para>
- •<param>
- •<paramref>
- •<permission>
- •<remarks>
- •<returns>
- •<seealso>
- •<summary>
- •<value>
- •Processing the documentation file
- •ID string format
- •ID string examples
- •An example
- •C# source code
- •Resulting XML
C# LANGUAGE SPECIFICATION
1• The program does not use either “::” or “->” operators. The “::” token is used only to separate a
2namespace alias from a member of the namespace, and the “->” operator is used in only a small fraction
3of programs (which involve unsafe code). The separator “.” is used in compound names such as
4Console.WriteLine.
5• The program does not contain forward declarations. Forward declarations are never needed, as
6declaration order is not significant.
7• The program does not use #include to import program text. Dependencies among programs are
8handled symbolically rather than textually. This approach eliminates barriers between applications
9written using multiple languages. For example, the Console class need not be written in C#.
108.2 Types
11C# supports two kinds of types: value types and reference types. Value types include simple types (e.g.,
12char, int, and float), enum types, and struct types. Reference types include class types, interface types,
13delegate types, and array types.
14Value types differ from reference types in that variables of the value types directly contain their data,
15whereas variables of the reference types store references to objects. With reference types, it is possible for
16two variables to reference the same object, and thus possible for operations on one variable to affect the
17object referenced by the other variable. With value types, the variables each have their own copy of the data,
18and it is not possible for operations on one to affect the other.
19The example
20using System;
21struct Struct1
22{
23public int Value;
24}
25class Class1
26{
27public int Value = 0;
28}
29class Test
30{
31 |
static void Main() { |
32 |
Struct1 val1 = new Struct1(); |
33 |
Struct1 val2 = val1; |
34 |
val2.Value = 123; |
35 |
Class1 ref1 = new Class1(); |
36 |
Class1 ref2 = ref1; |
37 |
ref2.Value = 123; |
38 |
Console.WriteLine("Values: {0}, {1}", val1.Value, val2.Value); |
39 |
Console.WriteLine("Refs: {0}, {1}", ref1.Value, ref2.Value); |
40}
41}
42shows this difference. The output produced is
43Values: 0, 123
44Refs: 123, 123
45The assignment to a field of the local variable val2 does not impact the local variable val1 because both
46local variables are of a value type (the type Struct1) and each local variable of a value type has its own
47storage. In contrast, the assignment ref2.Value = 123; affects the object that both ref1 and ref2
48reference.
49The lines
50Console.WriteLine("Values: {0}, {1}", val1.Value, val2.Value);
51Console.WriteLine("Refs: {0}, {1}", ref1.Value, ref2.Value);
16
Chapter 8 Language overview
1deserve further comment, as they demonstrate some of the string formatting behavior of
2Console.WriteLine, which, in fact, takes a variable number of arguments. The first argument is a string,
3which can contain numbered placeholders like {0} and {1}. Each placeholder refers to a trailing argument
4with {0} referring to the second argument, {1} referring to the third argument, and so on. Before the output
5is sent to the console, each placeholder is replaced with the formatted value of its corresponding argument.
6Developers can define new value types through enum and struct declarations, and can define new reference
7types via class, interface, and delegate declarations. The example
8using System;
9public enum Color
10{
11Red, Blue, Green
12}
13public struct Point
14{
15public int x, y;
16}
17public interface IBase
18{
19void F();
20}
21public interface IDerived: IBase
22{
23void G();
24}
25public class A
26{
27 |
protected virtual void H() { |
28 |
Console.WriteLine("A.H"); |
29}
30}
31public class B: A, IDerived
32{
33 |
public void F() { |
34 |
Console.WriteLine("B.F, implementation of IDerived.F"); |
35 |
} |
36 |
public void G() { |
37 |
Console.WriteLine("B.G, implementation of IDerived.G"); |
38 |
} |
39 |
override protected void H() { |
40 |
Console.WriteLine("B.H, override of A.H"); |
41}
42}
43public delegate void EmptyDelegate();
44shows an example of each kind of type declaration. Later clauses describe type declarations in detail.
458.2.1 Predefined types
46C# provides a set of predefined types, most of which will be familiar to C and C++ developers.
47The predefined reference types are object and string. The type object is the ultimate base type of all
48other types. The type string is used to represent Unicode string values. Values of type string are
49immutable.
50The predefined value types include signed and unsigned integral types, floating-point types, and the types
51bool, char, and decimal. The signed integral types are sbyte, short, int, and long; the unsigned
52integral types are byte, ushort, uint, and ulong; and the floating-point types are float and double.
17
C# LANGUAGE SPECIFICATION
1The bool type is used to represent boolean values: values that are either true or false. The inclusion of bool
2makes it easier to write self-documenting code, and also helps eliminate the all-too-common C++ coding
3error in which a developer mistakenly uses “=” when “==” should have been used. In C#, the example
4int i = …;
5F(i);
6if (i = 0) // Bug: the test should be (i == 0)
7G();
8 results in a compile-time error because the expression i = 0 is of type int, and if statements require an
9expression of type bool.
10The char type is used to represent Unicode code units. A variable of type char represents a single 16-bit
11Unicode code unit.
12The decimal type is appropriate for calculations in which rounding errors caused by floating point
13representations are unacceptable. Common examples include financial calculations such as tax computations
14and currency conversions. The decimal type provides for at least 28 significant digits.
15The table below lists the predefined types, and shows how to write literal values for each of them.
16
Type |
Description |
Example |
|
|
|
object |
The ultimate base type of all other types |
object o = null; |
|
|
|
string |
String type; a string is a sequence of Unicode code |
string s = "hello"; |
|
units |
|
|
|
|
sbyte |
8-bit signed integral type |
sbyte val = 12; |
|
|
|
short |
16-bit signed integral type |
short val = 12; |
|
|
|
int |
32-bit signed integral type |
int val = 12; |
|
|
|
long |
64-bit signed integral type |
long val1 = 12; |
|
|
long val2 = 34L; |
|
|
|
byte |
8-bit unsigned integral type |
byte val1 = 12; |
|
|
|
ushort |
16-bit unsigned integral type |
ushort val1 = 12; |
|
|
|
uint |
32-bit unsigned integral type |
uint val1 = 12; |
|
|
uint val2 = 34U; |
ulong |
64-bit unsigned integral type |
ulong val1 = 12; |
|
|
ulong val2 = 34U; |
|
|
ulong val3 = 56L; |
|
|
ulong val4 = 78UL; |
|
|
|
float |
Single-precision floating point type |
float val = 1.23F; |
|
|
|
double |
Double-precision floating point type |
double val1 = 1.23; |
|
|
double val2 = 4.56D; |
|
|
|
bool |
Boolean type; a bool value is either true or false |
bool val1 = true; |
|
|
bool val2 = false; |
|
|
|
char |
Character type; a char value is a Unicode code unit |
char val = 'h'; |
|
|
|
decimal |
Precise decimal type with at least 28 significant digits |
decimal val = 1.23M; |
|
|
|
17
18Each of the predefined types is shorthand for a system-provided type. For example, the keyword int refers
19to the struct System.Int32. As a matter of style, use of the keyword is favored over use of the complete
20system type name.
21Predefined value types such as int are treated specially in a few ways but are for the most part treated
22exactly like other structs. Operator overloading enables developers to define new struct types that behave
23much like the predefined value types. For instance, a Digit struct can support the same mathematical
18
Chapter 8 Language overview
1operations as the predefined integral types, and can define conversions between Digit and predefined
2types.
3The predefined types employ operator overloading themselves. For example, the comparison operators ==
4and != have different semantics for different predefined types:
5• Two expressions of type int are considered equal if they represent the same integer value.
6• Two expressions of type object are considered equal if both refer to the same object, or if both are
7null.
8• Two expressions of type string are considered equal if the string instances have identical lengths and
9identical characters in each character position, or if both are null.
10The example
11using System;
12class Test
13{
14 |
static void Main() { |
15 |
string s = "Test"; |
16 |
string t = string.Copy(s); |
17 |
Console.WriteLine(s == t); |
18 |
Console.WriteLine((object)s == (object)t); |
19}
20}
21produces the output
22True
23False
24because the first comparison compares two expressions of type string, and the second comparison
25compares two expressions of type object. (Note that when the Standard Library produces a string
26representation of a Boolean value, as is the case with System.WriteLine above, it uses “True” and
27“False”, while the corresponding C# language Boolean literals are spelled true and false.)
288.2.2 Conversions
29The predefined types also have predefined conversions. For instance, conversions exist between the
30predefined types int and long. C# differentiates between two kinds of conversions: implicit conversions
31and explicit conversions. Implicit conversions are supplied for conversions that can safely be performed
32without careful scrutiny. For instance, the conversion from int to long is an implicit conversion. This
33conversion always succeeds, and never results in a loss of information. The following example
34using System;
35class Test
36{
37 |
static void Main() { |
38 |
int intValue = 123; |
39 |
long longValue = intValue; |
40 |
Console.WriteLine("{0}, {1}", intValue, longValue); |
41}
42}
43implicitly converts an int to a long.
44In contrast, explicit conversions are performed with a cast expression. The example
45using System;
19