I'd like to create a generic method for converting any System.Enum derived type to its corresponding integer value, without casting and preferably without parsing a string.
Eg, what I want is something like this:
// Trivial example, not actually what I'm doing. class Converter { int ToInteger(System.Enum anEnum) { (int)anEnum; } }
But this doesn't appear to work. Resharper reports that you can not cast expression of type 'System.Enum' to type 'int'.
Now I've come up with this solution but I'd rather have something more efficient.
class Converter { int ToInteger(System.Enum anEnum) { return int.Parse(anEnum.ToString("d")); } }
Any suggestions?
Overview. To convert an enum to int , we can: Typecast the enum value to int . Use the ToInt32 method of the Convert class.
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.
An Enum value cannot be treated as an int by default because then you would be able to provide any integer and there would be no compile time check to validate that the provided integer does in fact exist as a value in the Enumeration.
If you don't want to cast,
Convert.ToInt32()
could do the trick.
The direct cast (via (int)enumValue
) is not possible. Note that this would also be "dangerous" since an enum can have different underlying types (int
, long
, byte
...).
More formally: System.Enum
has no direct inheritance relationship with Int32
(though both are ValueType
s), so the explicit cast cannot be correct within the type system
I got it to work by casting to an object and then to an int:
public static class EnumExtensions { public static int ToInt(this Enum enumValue) { return (int)((object)enumValue); } }
This is ugly and probably not the best way. I'll keep messing with it, to see if I can come up with something better....
EDIT: Was just about to post that Convert.ToInt32(enumValue) works as well, and noticed that MartinStettner beat me to it.
public static class EnumExtensions { public static int ToInt(this Enum enumValue) { return Convert.ToInt32(enumValue); } }
Test:
int x = DayOfWeek.Friday.ToInt(); Console.WriteLine(x); // results in 5 which is int value of Friday
EDIT 2: In the comments, someone said that this only works in C# 3.0. I just tested this in VS2005 like this and it worked:
public static class Helpers { public static int ToInt(Enum enumValue) { return Convert.ToInt32(enumValue); } } static void Main(string[] args) { Console.WriteLine(Helpers.ToInt(DayOfWeek.Friday)); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With