fluter
fluter

Reputation: 13796

Why is Enum string value inconsistent?

I have a enum, with members that are same value, but when I tried to print them as strings, I expected to see it uses the first defined value, that is, for Buy and Bid it prints Buy, and for Sell and Ask it prints Sell, but the test shows it looks they are randomly chosen, as it is neither first nor last for all values. so why is this inconsistence?

Sample code:

using System;

public enum OrderType
{
    Buy,
    Bid = Buy,
    Sell,
    Ask = Sell
}

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        OrderType o = OrderType.Buy;
        Console.WriteLine("{0}: {1}", (int)o, o);
        OrderType o2 = OrderType.Bid;
        Console.WriteLine("{0}: {1}", (int)o2, o2);
        OrderType o3 = OrderType.Sell;
        Console.WriteLine("{0}: {1}", (int)o3, o3);
        OrderType o4 = OrderType.Ask;
        Console.WriteLine("{0}: {1}", (int)o4, o4);
    }
}

Output:

Buy: 0 - Bid
Bid: 0 - Bid
Sell: 1 - Sell
Ask: 1 - Sell

Upvotes: 7

Views: 146

Answers (1)

Ray Toal
Ray Toal

Reputation: 88378

Rather than being inconsistent, you should think of this as being a case of a selection being made arbitrarily.

You have made an enum in which two enum values stand in for the integer 0, and two values stand in for the integer 1. So when you ask "what enum value is associated with 0?" there are two possible answers.

The designers of C# could have answered this question by:

  • throwing an error
  • answering with the enum value that appears first in the declaration
  • answering with the enum value that appears last in the declaration
  • answering with an arbitrary value

Language designers will sometimes go the "arbitrary" route because it leaves more room for optimization. For example they could put the integer-to-enum mapping in a hash table or something and let the lookup return whatever is most convenient. And this allows them to change their mapping strategy later on and return something else without breaking behaviors relative to the spec.

If they defined the language to produce a value that was sensitive to the declaration order, it might have put a little burden on the implementation and basically ended up with one more rule to keep track of.

I actually would have expected the answer to be "choose an arbitrary value" so I am kind of happy to see C# fits in with my expectations. But we're all different and yes, some people will be surprised. :)

Upvotes: 5

Related Questions