user1618825
user1618825

Reputation:

C# Same Enum Name with Multiple Values

How to add same Enum name for different values like this? Any possible implementation for this?

public enum Location
{
   A = 1,
   A = 2,
   A = 3,
   B = 4,
   B = 5  
}

Update:

I have a db table and from that i need to create Enum for Id from that table. I need to assign same names for some Id's. So that i need this kind of implementation. By passing the Id as value to get the Enum name.

Upvotes: 3

Views: 9249

Answers (4)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239804

If the only aspect of an enum that you're using is the Enum.GetName function, to translate an int into a string, then you don't need an enum - you just need a properly initialised Dictionary<int,string>, e.g.

public static Dictionary<int,string> Location = new Dictionary<int,string>
{
  {1,"A"},
  {2,"A"},
  {3,"A"},
  {4,"B"},
  {5,"B"}
}

And you can now just access Location[Id] rather than using GetName.

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186823

This is not possible; the explanation is quite simple: just imagine the code:

  int loc = (int) (Location.A);

What should the loc be? 1, 2 or 3? However, you can assign aliases: many names for one value:

  public enum Location
  {
   A = 1,
   B = 1,
   C = 1,
   D = 2,
   E = 2,
   F = 3 
  }

In case you convert from int back to enum

   Location loc = (Location) 2; // <- Location.D

there'll be the first enum value with corresponding int value (Location.D in the case)

Upvotes: 0

Mehrdad Kamelzadeh
Mehrdad Kamelzadeh

Reputation: 1784

As @Lasse Said it is not possible. but for your job you can create your own custom type so.

public class customtype
{
    public string Key { get; set; }
    public List<int> values { get; set; } 

}

Upvotes: 0

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391634

No, this is not possible. The enum names has to be unique.

Their values, however, can be duplicates, so you can do the reverse thing:

A = 1,
B = 2,
C = 2,
D = 1

Upvotes: 6

Related Questions