
21 Enums
21.3 Enum members
Paragraph 11 The body of an enum type declaration defines zero or more enum members, which are the named constants of the enum type. 2 No two enum members can have the same name. enum-member-declarations : enum-member-declaration enum-member-declarations , enum-member-declaration enum-member-declaration : attributesopt identifier attributesopt identifier = constant-expression
Paragraph 21 Each enum member has an associated constant value. 2 The type of this value is the underlying type for the containing enum. 3 The constant value for each enum member must be in the range of the underlying type for the enum. [Example: The example
enum Color: uint
{
Red = -1,
Green = -2,
Blue = -3
}
results in a compile-time error because the constant values -1, -2, and -3 are not in the range of the underlying integral type uint. end example]
Paragraph 31 Multiple enum members may share the same associated value. [Example: The example
enum Color
{
Red,
Green,
Blue,
Max = Blue
}
shows an enum that has two enum members-Blue and Max-that have the same associated value. end example]
Paragraph 41 The associated value of an enum member is assigned either implicitly or explicitly. 2 If the declaration of the enum member has a constant-expression initializer, the value of that constant expression, implicitly converted to the underlying type of the enum, is the associated value of the enum member. 3 If the declaration of the enum member has no initializer, its associated value is set implicitly, as follows:
using System;
enum Color
{
Red,
Green = 10,
Blue
}
class Test
{
static void Main() {
Console.WriteLine(StringFromColor(Color.Red));
Console.WriteLine(StringFromColor(Color.Green));
Console.WriteLine(StringFromColor(Color.Blue));
}
static string StringFromColor(Color c) {
switch (c) {
case Color.Red:
return String.Format("Red = {0}", (int) c);
case Color.Green:
return String.Format("Green = {0}", (int) c);
case Color.Blue:
return String.Format("Blue = {0}", (int) c);
default:
return "Invalid color";
}
}
}
prints out the enum member names and their associated values. The output is: Red = 0 Green = 10 Blue = 11for the following reasons:
enum Circular
{
A = B,
B
}
results in a compile-time error because the declarations of A and B are circular. A depends on B explicitly, and B depends on A implicitly. end example]
Paragraph 61 Enum members are named and scoped in a manner exactly analogous to fields within classes. 2 The scope of an enum member is the body of its containing enum type. 3 Within that scope, enum members can be referred to by their simple name. 4 From all other code, the name of an enum member must be qualified with the name of its enum type. 5 Enum members do not have any declared accessibility-an enum member is accessible if its containing enum type is accessible.
| |
| Jagger Software Ltd | |
| Company # 4070126 | |
| VAT # 762 5213 42 |