0

I am struggling with the correct cast. May someone can show me the right direction?

See my example below:

public enum E_Enum1
{
Value1,
Value2,
Value3
}

public enum E_Enum2
{
Bla,
blubb,
whatever
}

public void myMethod(Enum e)
{
//print e.value in int
//print e.toString()
}


myMethod(E_Enum2.whatever);
myMethod(E_Enum1.Value2);

I want to get a result of:

2
whatever
1
Value2
2
  • Ok, i think i had a other issue. it seems to work now with Convert.toInt(e) and e.toString() dont know Commented Sep 14, 2020 at 10:53
  • 1
    If you pass enum value as Enum, CLR will box the value. Use generic type to avoid boxing. Commented Sep 14, 2020 at 10:59

1 Answer 1

5

EDIT: Changed answer to avoid using string interpolation and string.Format that box the enum value

Use generic type:

public void myMethod<TEnum>(TEnum e) where TEnum : Enum
{
    Console.WriteLine(e.ToString("D"));
    Console.WriteLine(e.ToString("G"));
}

Then call method:

myMethod(E_Enum2.whatever);
myMethod(E_Enum1.Value2);
Sign up to request clarification or add additional context in comments.

3 Comments

Just for reference: Enumeration format strings (feel free to use in answer)
Alternative: Console.WriteLine(Convert.ToInt32(e)); Console.WriteLine(e.ToString());
Convert.ToInt32(e) will box the enum value, but it does remind me, because the type is constrained, we should just use .ToString().

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.