0

I am learning C#, and using visual studio. I try to specify identical values for multiple enumeration values by using one value as the underlying value of another.

namespace ConsoleApp1
{
    enum test
    {
        east = 0,
        west = east,
        south = 2,
        north = 3
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            test myTest1 = test.east;
            Console.WriteLine($"{myTest1}:{(byte)myTest1}");
            Console.ReadKey();
        }
    }
}

It output:west:0

namespace ConsoleApp1
{
    enum test
    {
        east = 0,
        west = 1,
        south = east,
        north = 3
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            test myTest1 = test.east;
            Console.WriteLine($"{myTest1}:{(byte)myTest1}");
            Console.ReadKey();
        }
    }
}

follow the output above, I thought it should be south:0. But it turns out east:0. Why is that?

SnowZ
  • 9
  • 2
  • 1
    Duplicate of: [Using an enum having entries with the same value of underlying type](https://stackoverflow.com/questions/26321509/using-an-enum-having-entries-with-the-same-value-of-underlying-type) and [GetName for enum with duplicate values](https://stackoverflow.com/q/9754604/8967612). – 41686d6564 stands w. Palestine Oct 19 '22 at 18:05
  • @41686d6564standsw.Palestine I would argue that while that potential duplicate it useful, it does not in fact answer this question. This question is specifically asking _why_ that occurs, not _if_ it occurs. – David L Oct 19 '22 at 18:08
  • 1
    @DavidL The answer to the "why" question is "because the result cannot be guaranteed" as mentioned in the docs. And the answer to the "why is it not guaranteed?" question can be easily determined by checking the [source of the GetName method](https://referencesource.microsoft.com/#mscorlib/system/type.cs,1535), which is already explained in [this answer](https://stackoverflow.com/a/26321691/8967612) to one of the duplicates above. Edit: actually, it's briefly explained in [this answer](https://stackoverflow.com/a/26321734/8967612) too. – 41686d6564 stands w. Palestine Oct 19 '22 at 18:12
  • I don't think it is clear from that answer that the source is using a BinarySearch and I appreciate you linking the source. That's good enough for me. – David L Oct 19 '22 at 18:14

0 Answers0