- •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 21 Enums
121. Enums
2An enum type is a distinct type that declares a set of named constants. [Example: The example
3enum Color
4{
5 |
Red, |
6 |
Green, |
7Blue
8}
9declares an enum type named Color with members Red, Green, and Blue. end example]
1021.1 Enum declarations
11An enum declaration declares a new enum type. An enum declaration begins with the keyword enum, and
12defines the name, accessibility, underlying type, and members of the enum.
13enum-declaration:
14 |
attributesopt enum-modifiersopt enum identifier enum-baseopt enum-body ;opt |
15 enum-base:
16: integral-type
17enum-body:
18 |
{ |
enum-member-declarationsopt } |
19 |
{ |
enum-member-declarations , } |
20Each enum type has a corresponding integral type called the underlying type of the enum type. This
21underlying type shall be able to represent all the enumerator values defined in the enumeration. An enum
22declaration can explicitly declare an underlying type of byte, sbyte, short, ushort, int, uint, long or
23ulong. [Note: char cannot be used as an underlying type. end note] An enum declaration that does not
24explicitly declare an underlying type has an underlying type of int.
25[Example: The example
26enum Color: long
27{
28 |
Red, |
29 |
Green, |
30Blue
31}
32declares an enum with an underlying type of long. end example] [Note: A developer might choose to use an
33underlying type of long, as in the example, to enable the use of values that are in the range of long but not
34in the range of int, or to preserve this option for the future. end note]
35[Note: C# allows a trailing comma in an enum-body, just like it allows one in an array-initializer (§19.6).
36end note]
3721.2 Enum modifiers
38An enum-declaration can optionally include a sequence of enum modifiers:
39enum-modifiers:
40
41
enum-modifier
enum-modifiers enum-modifier
351
|
C# LANGUAGE SPECIFICATION |
1 |
enum-modifier: |
2 |
new |
3 |
public |
4 |
protected |
5 |
internal |
6private
7It is a compile-time error for the same modifier to appear multiple times in an enum declaration.
8The modifiers of an enum declaration have the same meaning as those of a class declaration (§17.1.1).
9However, the abstract and sealed modifiers are not permitted in an enum declaration. Enums cannot be
10abstract and do not permit derivation.
1121.3 Enum members
12The body of an enum type declaration defines zero or more enum members, which are the named constants
13of the enum type. No two enum members can have the same name.
14enum-member-declarations:
15 |
enum-member-declaration |
|
16 |
enum-member-declarations , enum-member-declaration |
|
17 |
enum-member-declaration: |
|
18 |
attributesopt |
identifier |
19 |
attributesopt |
identifier = constant-expression |
20Each enum member has an associated constant value. The type of this value is the underlying type for the
21containing enum. The constant value for each enum member shall be in the range of the underlying type for
22the enum. [Example: The example
23enum Color: uint
24{
25 |
Red = |
-1, |
26 |
Green |
= -2, |
27Blue = -3
28}
29results in a compile-time error because the constant values -1, -2, and –3 are not in the range of the
30underlying integral type uint. end example]
31Multiple enum members can share the same associated value. [Example: The example
32enum Color
33{
34 |
Red, |
35 |
Green, |
36 |
Blue, |
37 |
|
38Max = Blue
39}
40shows an enum that has two enum members—Blue and Max—that have the same associated value. end
41example]
42The associated value of an enum member is assigned either implicitly or explicitly. If the declaration of the
43enum member has a constant-expression initializer, the value of that constant expression, implicitly
44converted to the underlying type of the enum, is the associated value of the enum member. If the declaration
45of the enum member has no initializer, its associated value is set implicitly, as follows:
46• If the enum member is the first enum member declared in the enum type, its associated value is zero.
47• Otherwise, the associated value of the enum member is obtained by increasing the associated value of
48the textually preceding enum member by one. This increased value shall be within the range of values
49that can be represented by the underlying type.
352
Chapter 21 Enums
1[Example: The example
2using System;
3enum Color
4{
5 |
Red, |
6 |
Green = 10, |
7Blue
8}
9class Test
10{
11 |
static void Main() { |
12 |
Console.WriteLine(StringFromColor(Color.Red)); |
13 |
Console.WriteLine(StringFromColor(Color.Green)); |
14 |
Console.WriteLine(StringFromColor(Color.Blue)); |
15 |
} |
16 |
static string StringFromColor(Color c) { |
17 |
switch (c) { |
18 |
case Color.Red: |
19 |
return String.Format("Red = {0}", (int) c); |
20 |
case Color.Green: |
21 |
return String.Format("Green = {0}", (int) c); |
22 |
case Color.Blue: |
23 |
return String.Format("Blue = {0}", (int) c); |
24 |
default: |
25 |
return "Invalid color"; |
26 |
} |
27}
28}
29prints out the enum member names and their associated values. The output is:
30Red = 0
31Green = 10
32Blue = 11
33for the following reasons:
34• the enum member Red is automatically assigned the value zero (since it has no initializer and is the first
35enum member);
36• the enum member Green is explicitly given the value 10;
37• and the enum member Blue is automatically assigned the value one greater than the member that
38textually precedes it.
39end example]
40The associated value of an enum member shall not, directly or indirectly, use the value of its own associated
41enum member. Other than this circularity restriction, enum member initializers can freely refer to other
42enum member initializers, regardless of their textual position. Within an enum member initializer, values of
43other enum members are always treated as having the type of their underlying type, so that casts are not
44necessary when referring to other enum members.
45[Example: The example
46enum Circular
47{
48 |
A = B, |
49B
50}
51results in a compile-time error because the declarations of A and B are circular. A depends on B explicitly,
52and B depends on A implicitly. end example]
353
C# LANGUAGE SPECIFICATION
1Enum members are named and scoped in a manner exactly analogous to fields within classes. The scope of
2an enum member is the body of its containing enum type. Within that scope, enum members can be referred
3to by their simple name. From all other code, the name of an enum member shall be qualified with the name
4of its enum type. Enum members do not have any declared accessibility—an enum member is accessible if
5its containing enum type is accessible.
621.4 The System.Enum type
7The type System.Enum is the abstract base class of all enum types (this is distinct and different from the
8underlying type of the enum type), and the members inherited from System.Enum are available in any
9enum type. A boxing conversion (§11.3.1) exists from any enum type to System.Enum, and an unboxing
10conversion (§11.3.2) exists from System.Enum to any enum type.
11Note that System.Enum is not itself an enum-type. Rather, it is a class-type from which all enum-types are
12derived. The type System.Enum inherits from the type System.ValueType (§11.1.1), which, in turn,
13inherits from type object. At run-time, a value of type System.Enum can be null or a reference to a
14boxed value of any enum type.
1521.5 Enum values and operations
16Each enum type defines a distinct type; an explicit enumeration conversion (§13.2.2) is required to convert
17between an enum type and an integral type, or between two enum types. The set of values that an enum type
18can take on is not limited by its enum members. In particular, any value of the underlying type of an enum
19can be cast to the enum type, and is a distinct valid value of that enum type.
20Enum members have the type of their containing enum type (except within other enum member initializers:
21see §21.3). The value of an enum member declared in enum type E with associated value v is (E)v.
22The following operators can be used on values of enum types: ==, !=, <, >, <=, >= (§14.9.5), + (§14.7.4),
23- (§14.7.5), ^, &, | (§14.10.2), ~ (§14.6.4), ++, -- (§14.5.9 and §14.6.5), and sizeof (§25.5.4).
24Every enum type automatically derives from the class System.Enum (which, in turn, derives from
25System.ValueType and object). Thus, inherited methods and properties of this class can be used on
26values of an enum type.
354
