Victor Mukherjee
Victor Mukherjee

Reputation: 11085

Behaviour of enum in c#

 class MainClass
{
    static void Main(String[] args)
    {
        Fruits f =Fruits.Banana;
        Console.WriteLine("Fruit={0}",f);
        Console.Read();
    }

    private enum Fruits
    {
        Banana=0,
        Apple=0,
        Orange=0,
        Cherries
    }

}

The above code gives output: Fruit=Apple

If I change the value of Banana to anything other than 0 within enum, the output is Banana. My question is why in the first case, the output is Apple and not Orange or Banana itself?

Upvotes: 1

Views: 174

Answers (2)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239824

Internally, an enum is very like a struct with a single internal field - having the same type as the base type for the enum (here, int), which stores the value.

That's it, so far as an enum is concerned. It has no storage for anything else - it does not know how it was constructed - whether by using a named value from the enumeration, or by casting from the base type, or any other means.

As such, when you ask for a string representation, it has no further information to go on than to take the numeric value and attempt to find a name among its enumeration members that matches that value.

I'm not sure whether it's defined which value will be selected if multiple members have the same numeric value, but it's got to pick something, and it at least appears to be consistent.


In fact, Enum.ToString() says:

If multiple enumeration members have the same underlying value and you attempt to retrieve the string representation of an enumeration member's name based on its underlying value, your code should not make any assumptions about which name the method will return.

Upvotes: 2

Cole Tobin
Cole Tobin

Reputation: 9425

Why are you even doing something like that? Anyways, it's because internally, enums with the same value are chosen alphabetically.

Upvotes: 2

Related Questions