Cannot convert type 'System.Enum' to int

Viewed 37415

(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').

8 Answers

For me it was enough to cast to object first, since it's just a compilation error.

public static int AsInt(this Enum @this)
{
  return (int)(object)@this;
}
Related