user191152
user191152

Reputation:

Why do enums behave this way?

I experienced some slightly odd behaviour today from the C# compiler, when fiddling with Enums.

enum FunWithEnum
{
    One = 1,
    Two,
    Three,
    Four = 1,
    Five = 2,
    Six
}

Result:

Can someone explain to me why the values are what they are once compiled ?

My initial guess has to do with being able to have aliases when using the enum. But I don't know if that makes sense.

Upvotes: 1

Views: 135

Answers (2)

James
James

Reputation: 9985

According to the docs

the value of each successive enumerator is increased by 1.

On this basis

One = 1,
Two,  // = 2
Three,  // = 3
Four = 1,
Five = 2,
Six //== 3

And also from the answer to the other question

It's undefined what ToString will return when multiple enums have the same value

Upvotes: 5

Tigran
Tigran

Reputation: 62265

The values I see in code provided are never assigned by compiler, it's a written by a coder. So

  • or it's a bug leading to a mess (there is no much sence in having different enum members with the same associated numbers)
  • or it is a code that deals with some old/legacy system, where the developer has to introduce some new values (for commodity of development or for 1000 other reasons) but remaining backcompatible with the system itself. So this is kind of workarround to extend functionality of some very old code that could not be touched.

Upvotes: 2

Related Questions