Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enums, overlapping values, C#

Tags:

c++

c

c#

enums

Apologies in advance as I'm sure someone must have asked this before but I can't find it.

Just had a surprise, a colleague and I both added the same value in for an enum, and it compiled, e.g.

  enum MyEnum
  {
    mine = 1,
    his = 1
  }

Looks like C/C++ supports this also (?). Any reason for this behaviour, any cases where it's useful? I saw one case with difference human languages (one = 1, eins = 1, etc) but I'm not convinced

Thanks

like image 479
tony Avatar asked Oct 07 '11 10:10

tony


People also ask

Can enum have duplicate values?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

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 two enums have the same value C#?

Since there is no problem with a type that contains an multiple constants that have the same value, there is no problem with the enum definition. But since the enum does not have unique values you might have an issue when converting into this enum.

Can enum have duplicate values C++?

There is currently no way to detect or prevent multiple identical enum values in an enum.


1 Answers

Let's take a simple example

enum PrivilegeLevel
{
    None,
    Reporter,
    Reviewer,
    Admin,
    DefaultForNewUser = None,
    DefaultForProjectOwner = Reviewer,
};
like image 90
crazyjul Avatar answered Oct 05 '22 11:10

crazyjul