2

Can we make a enum as a generic data type? If so please provide an example. Thanks in advance.

Regent
  • 5,502
  • 3
  • 33
  • 59
HotTester
  • 5,620
  • 15
  • 63
  • 97
  • 2
    What exactly do you want to use it for? – Oded Jan 28 '10 at 09:47
  • We are having many enums in our project which come under various category like the types of domestic meters, commercial meters etc, now instead of mapping the usual integar value to the name we were thinking of mapping the meter code with it. Hence I thought if the enums could be generic we could make classes of meter types and create generic enums. I hope it clear my question. – HotTester Jan 28 '10 at 09:56

4 Answers4

7

Enums cannot be made generic.

From MSDN:

An enumeration is a named constant whose underlying type is any integral type

See this SO answer for an alternative.

Community
  • 1
  • 1
Oded
  • 489,969
  • 99
  • 883
  • 1,009
2

No. Enums in C# have an integral base type (Int32 by default) but the items in it are always known at compile-time. There is simply no sensible way how generics might even fit into the concept of an enum.

Joey
  • 344,408
  • 85
  • 689
  • 683
1

You can try class enums.

Arnis Lapsa
  • 45,880
  • 29
  • 115
  • 195
0

You can pass an enum as a type parameter to a generic method whose constraints allow it, but the enum itself cannot be generic.

Jay
  • 56,361
  • 10
  • 99
  • 123