Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the Integer value of an enumeration which is a generic

Here is the basic situation.

Public Class MyEnumClass(of T)
   Public MyValue as T
End Class

This is vast oversimplification of the actual class, but basically I know that T is an enumeration (if it is not then there will be many other problems, and is a logical error made by the programmer)

Basically I want to get the underlying integer value of MyValue.

Using Cint or Ctype, does not work.

like image 216
Ross Goddard Avatar asked Dec 18 '08 18:12

Ross Goddard


People also ask

How do you find the enum value of an integer?

To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

How do I find the value of an enum in a list?

The idea is to use the Enum. GetValues() method to get an array of the enum constants' values. To get an IEnumerable<T> of all the values in the enum, call Cast<T>() on the array. To get a list, call ToList() after casting.

How do you convert enum to int in Python?

Use the IntEnum class from the enum module to convert an enum to an integer in Python. You can use the auto() class if the exact value is unimportant. To get a value of an enum member, use the value attribute on the member.

Is enum generic?

The enum is a default subclass of the generic Enum<T> class, where T represents generic enum type. This is the common base class of all Java language enumeration types. The transformation from enum to a class is done by the Java compiler during compilation. This extension need not be stated explicitly in code.


4 Answers

I was going to use a cool piece of reflection code but just a simple Convert.ToInt32 works great... Forgive my VB I'm a C# guy

Public Function GetEnumInt(Of T)(enumVal As T) As Integer     Return Convert.ToInt32(enumVal) End Function 
like image 64
joshperry Avatar answered Oct 03 '22 22:10

joshperry


I tried this and it worked:

String.Format("{0:d}", MyValue) 
like image 23
Ross Goddard Avatar answered Oct 04 '22 00:10

Ross Goddard


I know you can do the following to get all the underlying values (I hope my VB syntax is correct... I've been working in C# mostly of late):

Dim intVal As Integer

For Each intVal In  [Enum].GetValues(GetType(T))
    //intValue is now the enum integer value
Next

That might at least get you started in the right direction.

like image 24
Jason Down Avatar answered Oct 03 '22 23:10

Jason Down


This also works : Fix(enumval)

like image 29
anefeletos Avatar answered Oct 04 '22 00:10

anefeletos