- •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
118.1.2 Struct interfaces
2A struct declaration can include a struct-interfaces specification, in which case the struct is said to
3implement the given interface types.
4struct-interfaces:
5: interface-type-list
6The handling of interfaces on multiple parts of a partial struct declaration (§17.1.4) are discussed further
7in §17.1.2.2.
8Interface implementations are discussed further in §20.4.
918.1.3 Struct body
10The struct-body of a struct defines the members of the struct.
11struct-body:
12{ struct-member-declarationsopt }
1318.2 Struct members
14The members of a struct consist of the members introduced by its struct-member-declarations and the
15members inherited from the type System.ValueType.
16struct-member-declarations:
17
18
19
20
21
22
23
24
25
26
27
28
29
struct-member-declaration
struct-member-declarations struct-member-declaration
struct-member-declaration: constant-declaration field-declaration method-declaration property-declaration event-declaration indexer-declaration operator-declaration constructor-declaration static-constructor-declaration type-declaration
30All kinds of class-member-declarations except destructor-declaration are also struct-member-declarations.
31Except for the differences noted in §18.3, the descriptions of class members provided in §17.1.4 through
32§17.11 apply to struct members as well.
3318.3 Class and struct differences
3418.3.1 Value semantics
35Structs are value types (§11.1) and are said to have value semantics. Classes, on the other hand, are reference
36types (§11.2) and are said to have reference semantics.
37A variable of a struct type directly contains the data of the struct, whereas a variable of a class type contains
38a reference to the data, the latter known as an object.
39With classes, it is possible for two variables to reference the same object, and thus possible for operations on
40one variable to affect the object referenced by the other variable. With structs, the variables each have their
41own copy of the data, and it is not possible for operations on one to affect the other. Furthermore, because
42structs are not reference types, it is not possible for values of a struct type to be null.
43[Example: Given the declaration
322
Chapter 18 Structs
1struct Point
2{
3 |
public int x, y; |
4 |
public Point(int x, int y) { |
5 |
this.x = x; |
6 |
this.y = y; |
7}
8}
9the code fragment
10Point a = new Point(10, 10);
11Point b = a;
12a.x = 100;
13System.Console.WriteLine(b.x);
14outputs the value 10. The assignment of a to b creates a copy of the value, and b is thus unaffected by the
15assignment to a.x. Had Point instead been declared as a class, the output would be 100 because a and b
16would reference the same object. end example]
1718.3.2 Inheritance
18All struct types implicitly inherit from System.ValueType, which, in turn, inherits from class object. A
19struct declaration can specify a list of implemented interfaces, but it is not possible for a struct declaration to
20specify a base class.
21Struct types are never abstract and are always implicitly sealed. The abstract and sealed modifiers are
22therefore not permitted in a struct declaration.
23Since inheritance isn’t supported for structs, the declared accessibility of a struct member cannot be
24protected or protected internal.
25Function members in a struct cannot be abstract or virtual, and the override modifier is allowed
26only to override methods inherited from the type System.ValueType.
2718.3.3 Assignment
28Assignment to a variable of a struct type creates a copy of the value being assigned. This differs from
29assignment to a variable of a class type, which copies the reference but not the object identified by the
30reference.
31Similar to an assignment, when a struct is passed as a value parameter or returned as the result of a function
32member, a copy of the struct is created. A struct can be passed by reference to a function member using a
33ref or out parameter.
34When a property or indexer of a struct is the target of an assignment, the instance expression associated with
35the property or indexer access shall be classified as a variable. If the instance expression is classified as a
36value, a compile-time error occurs. This is described in further detail in §14.13.1.
3718.3.4 Default values
38As described in §12.2, several kinds of variables are automatically initialized to their default value when
39they are created. For variables of class types and other reference types, this default value is null. However,
40since structs are value types that cannot be null, the default value of a struct is the value produced by
41setting all value type fields to their default value and all reference type fields to null.
42[Example: Referring to the Point struct declared above, the example
43Point[] a = new Point[100];
44initializes each Point in the array to the value produced by setting the x and y fields to zero. end example]
45The default value of a struct corresponds to the value returned by the default constructor of the struct
46(§11.1.1). Unlike a class, a struct is not permitted to declare a parameterless instance constructor. Instead,
323
C# LANGUAGE SPECIFICATION
1every struct implicitly has a parameterless instance constructor, which always returns the value that results
2from setting all value type fields to their default value and all reference type fields to null.
3[Note: Structs should be designed to consider the default initialization state a valid state. In the example
4using System;
5struct KeyValuePair
6{
7 |
string key; |
8 |
string value; |
9 |
public KeyValuePair(string key, string value) { |
10 |
if (key == null || value == null) throw new ArgumentException(); |
11 |
this.key = key; |
12 |
this.value = value; |
13}
14}
15the user-defined instance constructor protects against null values only where it is explicitly called. In cases
16where a KeyValuePair variable is subject to default value initialization, the key and value fields will be
17null, and the struct should be prepared to handle this state. end note]
1818.3.5 Boxing and unboxing
19A value of a class type can be converted to type object or to an interface type that is implemented by the
20class simply by treating the reference as another type at compile-time. Likewise, a value of type object or
21a value of an interface type can be converted back to a class type without changing the reference (but, of
22course, a run-time type check is required in this case).
23Since structs are not reference types, these operations are implemented differently for struct types. When a
24value of a struct type is converted to type object or to an interface type that is implemented by the struct, a
25boxing operation takes place. Likewise, when a value of type object or a value of an interface type is
26converted back to a struct type, an unboxing operation takes place. A key difference from the same
27operations on class types is that boxing and unboxing copies the struct value either into or out of the boxed
28instance. [Note: Thus, following a boxing or unboxing operation, changes made to the unboxed struct are not
29reflected in the boxed struct. end note]
30For further details on boxing and unboxing, see §11.3.
3118.3.6 Meaning of this
32Within an instance constructor or instance function member of a class, this is classified as a value. Thus,
33while this can be used to refer to the instance for which the function member was invoked, it is not
34possible to assign to this in a function member of a class.
35Within an instance constructor of a struct, this corresponds to an out parameter of the struct type, and
36within an instance function member of a struct, this corresponds to a ref parameter of the struct type. In
37both cases, this is classified as a variable, and it is possible to modify the entire struct for which the
38function member was invoked by assigning to this or by passing this as a ref or out parameter.
3918.3.7 Field initializers
40As described in §18.3.4, the default value of a struct consists of the value that results from setting all value
41type fields to their default value and all reference type fields to null. For this reason, a struct does not
42permit instance field declarations to include variable initializers. [Example: As such, the following example
43results in one or more compile-time errors:
44struct Point
45{
46 |
public int x = 1; // Error, initializer not permitted |
47public int y = 1; // Error, initializer not permitted
48}
49end example]
324
Chapter 18 Structs
1This restriction applies only to instance fields. Static fields of a struct are permitted to include variable
2initializers.
318.3.8 Constructors
4Unlike a class, a struct is not permitted to declare a parameterless instance constructor. Instead, every struct
5implicitly has a parameterless instance constructor, which always returns the value that results from setting
6all value type fields to their default value and all reference type fields to null (§11.1.1). A struct can declare
7instance constructors having parameters. [Example:
8struct Point
9{
10 |
int x, y; |
11 |
public Point(int x, int y) { |
12 |
this.x = x; |
13 |
this.y = y; |
14}
15}
16Given the above declaration, the statements
17Point p1 = new Point();
18Point p2 = new Point(0, 0);
19both create a Point with x and y initialized to zero. end example]
20A struct instance constructor is not permitted to include a constructor initializer of the form base(…).
21The this variable of a struct instance constructor corresponds to an out parameter of the struct type, and
22similar to an out parameter, this shall be definitely assigned (§12.3) at every location where the
23constructor returns. [Example: Consider the instance constructor implementation below:
24struct Point
25{
26 |
int x, |
y; |
|
27 |
public |
int X { |
|
28 |
set { x = value; } |
||
29 |
} |
|
|
30 |
public int Y { |
|
|
31 |
set { y = value; } |
||
32 |
} |
|
|
33 |
public Point(int x, int y) { |
||
34 |
X = x; |
// error, this is not yet definitely assigned |
|
35 |
Y = y; |
// error, this is not yet definitely assigned |
|
36}
37}
38No instance member function (including the set accessors for the properties X and Y) can be called until all
39fields of the struct being constructed have been definitely assigned. Note, however, that if Point were a
40class instead of a struct, the instance constructor implementation would be permitted.
41end example]
4218.3.9 Destructors
43A struct is not permitted to declare a destructor.
4418.3.10 Static constructors
45Static constructors for structs follow most of the same rules as for classes. The execution of a static
46constructor for a struct is triggered by the first of the following events to occur within an application
47domain:
48• An instance member of the struct is referenced.
325
