Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum with specified values for only some of the members

Tags:

c#

enums

I have an enum with custom value for only part of the list

public enum MyEnum
{
    FirstValue,
    SecondValue,
    ThirdValue,
    ForthValue = 1,
    FifthValue = 2
}

When I tried strina name = (MyEnum)2; name was ThirdValue.

But when I changed the enum to

public enum MyEnum
{
    FirstValue = 3,
    SecondValue,
    ThirdValue,
    ForthValue = 1,
    FifthValue = 2
}

In strina name = (MyEnum)2; name was FifthValue.

Does the compiler (I'm using Visual Studio 2012) initialize custom values only if the first has custom values?

And if ThirdValue got default value 2 in the first example how come there wasn't any error in FifthValue = 2?

like image 470
Guy Avatar asked Feb 04 '16 14:02

Guy


2 Answers

When you assign values for an enum member, the compiler increments the value by one for the next member, unless it's defined. If no members have values, the numbering starts at 0.

Your first example, with what the compiler is doing is:

public enum MyEnum
{
    FirstValue,    // == 0
    SecondValue,   // == 1
    ThirdValue,    // == 2
    ForthValue = 1,
    FifthValue = 2
}

so you have two members with value 2.

Either give them all values, or give them no values. Anything else will likely lead to confusion.

The C# standard, section 14.3 says (emphasis mine):

The associated value of an enum member is assigned either implicitly or explicitly. 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. If the declaration of the enum 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.
like image 114
Wai Ha Lee Avatar answered Oct 04 '22 19:10

Wai Ha Lee


The corresponding integer values that enum values map to always start at 0 unless you specifically change the values.

As such, your first piece of code is equivalent to this:

public enum MyEnum
{
    FirstValue = 0,
    SecondValue = 1,
    ThirdValue = 2,
    ForthValue = 1,
    FifthValue = 2
}

So you can see that 2 maps to both ThirdValue and FifthValue.

Your second example is equivalent to this:

public enum MyEnum
{
    FirstValue = 3,
    SecondValue = 4,
    ThirdValue = 5,
    ForthValue = 1,
    FifthValue = 2
}
like image 22
Lasse V. Karlsen Avatar answered Oct 04 '22 20:10

Lasse V. Karlsen