3

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.

15
  • 3
    Why would you want to do this? Commented Jul 30, 2013 at 6:08
  • Unique names, the values can be duplicates. Commented Jul 30, 2013 at 6:09
  • Need to map Db primary key Id with same name for some Id's and so need have enum Commented Jul 30, 2013 at 6:10
  • If we knew more about what problem you were trying to solve with this approach, we could guide you in the right direction. Commented Jul 30, 2013 at 6:10
  • 1
    How can your PK in your DB have duplicates? Commented Jul 30, 2013 at 6:11

4 Answers 4

6

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 
Sign up to request clarification or add additional context in comments.

Comments

0

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; } } 

3 Comments

Thanks, Regard of this we can just use Dictionary object itself. But i just need to know if that happens with enum.
You can't use an enum!
@SSS yea you can use. But I thought you might need to do some more manipulation. Unfortunately you can't do it with Enums!
0

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)

1 Comment

+1, Thanks for the detailed explanation. Is there any other simple possible implementation for my case?
0

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.

Comments