Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you have multiple enum values for the same integer? [duplicate]

Tags:

c#

.net

enums

clr

In .NET can you have multiple enum values for the same integer?

eg.

public enum PersonGender
    {
        Unknown = 0,
        Male = 1,
        Female = 2,
        Intersex = 3,
        Indeterminate = 3,
        NonStated = 9,
        InadequatelyDescribed = 9
    }
like image 595
CJ7 Avatar asked Mar 17 '13 06:03

CJ7


People also ask

Can enums have duplicate values?

CA1069: Enums should not have duplicate values.

Can we have enum containing enum with same constant?

The values assigned to the enum names must be integral constant, i.e., it should not be of other types such string, float, etc. All the enum names must be unique in their scope, i.e., if we define two enum having same scope, then these two enums should have different enum names otherwise compiler will throw an error.

Can enum store multiple variables?

The answer is no. You cannot store more that one value in an ENUM column.

Can an enum be a double?

Enums type can be an integer (float, int, byte, double etc.) but if you use beside int, it has to be cast. Enum is used to create numeric constants in . NET framework.


2 Answers

In C#, this is allowed, as per the C# Language Specication, version 4. Section 1.10 Enums doesn't explicitly mention the possibility but, later on in section 14 Enums, 14.3, we see:

Multiple enum members may share the same associated value. The example

enum Color {
   Red,
   Green,
   Blue,
   Max = Blue
}

shows an enum in which two enum members - Blue and Max - have the same associated value.

like image 105
paxdiablo Avatar answered Oct 06 '22 01:10

paxdiablo


That works fine. There is absolutely nothing wrong with the code you posted. It compiles just fine and works in code, with the caveat that

PersonGender.NonStated == PersonGender.InadequatelyDescribed
like image 30
p.s.w.g Avatar answered Oct 05 '22 23:10

p.s.w.g