Akkusativobjekt
Akkusativobjekt

Reputation: 2023

C# Enum Index Behavior

I stumbled over the following example code, but I could not really understand the behaviour behind it. I tried to find an explanation in the C# documentation, but wasn't successful.

enum Color { Red, Green = 3, Blue }
public class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine((Color) 1);
        Console.WriteLine((Color) 2);
        Console.WriteLine((Color) 3);
        Console.WriteLine((Color) 4);
        Console.WriteLine((Color) 5);   
   }
}}

The output of the code is:

1
2
Green
Blue
5

It appears that Blue gets the index of Green+1, but that in indexing only works upwards and not downwards. So why does the indexing works like this?

Upvotes: 0

Views: 87

Answers (2)

Neil
Neil

Reputation: 11889

Your code is effectively:

enum Color 
{ 
   Red = 0, Green = 3, Blue = 4 
}

It's just the compiler has filled in some of the values for you. If you are unsure of what values go where, just initialise them all manually every time. Sometimes, when an enum is large enough, you should probably do that anyway.

Upvotes: 1

johnny 5
johnny 5

Reputation: 20995

I could only speculate as to why, but It doesn't make sense for indexing to work both ways.

Imagine if you were to override the last index to be max value, and you were to set the first index as 0. It would be ambiguous to what the values in between would be, should it be incrementing or decrementing?

If you wanted it to work downwards all you would have to do is start with the earlier index. Specifying and index later gives you the options of using explicit indexes without having to worry about messing up the order

Upvotes: 0

Related Questions