Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert type 'System.Enum' to int

(OK, I'll expose the depths of my ignorance here, please be gentle)

Background

I've got a method which looks (a bit) like this:

public void AddLink(Enum enumVal) {      string identifier = m_EnumInterpreter(enumVal);      AddLink(identifier); } 

The EnumInterpreter is a Func<Enum, string> that is passed in when the parent class is created.

I'm using Enum because at this level it is 'none of my business'- I don't care which specific enum it is. The calling code just uses a (generated) enum to avoid magic strings.

Question

If the EnumInterpreter sends back an empty string, I'd like to throw an exception with the actual value of enumVal. I thought I would just be able to cast to int, but it the compiler won't have it. What am I doing wrong? (Please don't say 'everything').

like image 242
Benjol Avatar asked Oct 29 '09 13:10

Benjol


People also ask

Can we typecast enum to int?

Yes. In C enum types are just int s under the covers. Typecast them to whatever you want.

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.

How do I get an enum from an integer?

Use the Type Casting to Convert an Int to Enum in C# The correct syntax to use type casting is as follows. Copy YourEnum variableName = (YourEnum)yourInt; The program below shows how we can use the type casting to cast an int to enum in C#. We have cast our integer value to enum constant One .

Are enums ints?

I recently explained that although both C and C++ provide void * as the generic data pointer type, each language treats the type a little differently. For any object type T , both C and C++ let you implicitly convert an object of type T * to void * .


2 Answers

System.Enum cannot be directly cast to Integer, but it does explicitly implement IConvertible, meaning you can use the following:

public void AddLink(Enum enumVal) {     string identifier = m_EnumInterpreter(Convert.ToInt32(enumVal));     AddLink(identifier); } 

Keep in mind that if your Enum is actually using something other than an Integer (such as a float), you'll lose the non-integer data on conversion. Or obviously replace the Convert call with whatever you are converting from (if it's known)

like image 57
Ryan Brunner Avatar answered Oct 04 '22 06:10

Ryan Brunner


No, you aren't able to cast it to an int because System.Enum is not an enum, it's just the base class for enums.

EDIT:

You can get the value as follows, but it is ugly:

int intVar = (int)enuYourEnum.GetType().GetField("value__").GetValue(objYourEnum); 
like image 21
Maximilian Mayerl Avatar answered Oct 04 '22 06:10

Maximilian Mayerl