X hits on this document

1034 views

0 shares

0 downloads

0 comments

305 / 396

C# LANGUAGE SPECIFICATION

member has no initializer, its associated value is set implicitly, as follows:

If the enum member is the first enum member declared in the enum type, its associated value is zero.

Otherwise, the associated value of the enum member is obtained by increasing the associated value of the textually preceding enum member by one. This increased value must be within the range of values that can be represented by the underlying type, otherwise a compile-time error occurs.

The example

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 = 11

for the following reasons:

the enum member Red is automatically assigned the value zero (since it has no initializer and is the first enum member);

the enum member Green is explicitly given the value 10;

and the enum member Blue is automatically assigned the value one greater than the member that textually precedes it.

The associated value of an enum member may not, directly or indirectly, use the value of its own associated enum member. Other than this circularity restriction, enum member initializers may freely refer to other enum

292Copyright Microsoft Corporation 1999-2003. All Rights Reserved.

Document info
Document views1034
Page views1034
Page last viewedSat Dec 10 06:17:08 UTC 2016
Pages396
Paragraphs9401
Words133190

Comments