Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does C# decide which enum value as a returned one? Any rules? [duplicate]

Tags:

c#

.net

enums

I found a very intersting thing——Let's say:

 enum Myenum { a, b, c= 0 }
    public class Program
    {
        static void Main(string[] args)
        {
            Myenum ma = Myenum.a;
            Console.WriteLine(ma);
        }
    }

The result is a, why?

And if I say:

 enum Myenum { a, b=0, c}
    public class Program
    {
        static void Main(string[] args)
        {
            Myenum ma = Myenum.a;
            Console.WriteLine(ma);
        }
    }

The result becomes "b", why?

like image 206
xqMogvKW Avatar asked Sep 26 '14 09:09

xqMogvKW


People also ask

How does C operate?

The C programming language works by writing your code into an executable file. The C compiler will take that executable and convert it in its entirety into machine code that will then be executed by your computer at runtime.

What does %c mean in C programming?

While it's an integer, the %c interprets its numeric value as a character value for display. For instance for the character a : If you used %d you'd get an integer, e.g., 97, the internal representation of the character a. vs. using %c to display the character ' a ' itself (if using ASCII)

How does C run?

Execution FlowThe preprocessor generates an expanded source code. 2) Expanded source code is sent to compiler which compiles the code and converts it into assembly code. 3) The assembly code is sent to assembler which assembles the code and converts it into object code.

How do you explain C?

C is what is called a compiled language. This means that once you write your C program, you must run it through a C compiler to turn your program into an executable that the computer can run (execute).


1 Answers

From Enum.ToString:

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. For example, the following enumeration defines two members, Shade.Gray and Shade.Grey, that have the same underlying value.

Related: enum.ToString return wrong value?

So i would assign unique values if you wannt to rely on the name:

enum Myenum { hello = 1, world = 2, qiang = 3 }
like image 185
Tim Schmelter Avatar answered Oct 26 '22 23:10

Tim Schmelter