Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Values of Enum types

Tags:

c#

enums

I'm just wondering why I get this output :

enum MyEnum {     a=1,     b=2,     c=3,     d=3,     f=d } Console.WriteLine(MyEnum.f.ToString()); 

OUTPUT
c


But in Mono
OUTPUT
f

So why is the output c? not d? How does the compiler choose c? If I change the code like this:

enum MyEnum {     a=1,     b=2,     c=3,     d=3,      k=3 } Console.WriteLine(MyEnum.k.ToString()); 


OUTPUT
c
again!

Another example:

enum MyEnum {     a=3,     b=3,     c=3,           d=3,     f=d,    } MessageBox.Show(MyEnum.f.ToString()); 

OUTPUT
c

like image 1000
Mustafa Ekici Avatar asked Oct 26 '11 00:10

Mustafa Ekici


People also ask

What type are enum values?

An enum type is a distinct value type (§8.3) that declares a set of named constants. declares an enum type named Color with members Red , Green , and Blue .

What are the values in an enum called?

In computer programming, an enumerated type (also called enumeration, enum, or factor in the R programming language, and a categorical variable in statistics) is a data type consisting of a set of named values called elements, members, enumeral, or enumerators of the type.

Can enums have a value?

By default enums have their own string values, we can also assign some custom values to enums.

How do I get a list of all enum values?

The idea is to use the Enum. GetValues() method to get an array of the enum constants' values. To get an IEnumerable<T> of all the values in the enum, call Cast<T>() on the array. To get a list, call ToList() after casting.


1 Answers

From MSDN:

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.

See: http://msdn.microsoft.com/en-us/library/a0h36syw.aspx#Y300

like image 174
Daryl Avatar answered Sep 22 '22 03:09

Daryl