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
Fildor
  • 14,510
  • 4
  • 35
  • 67
Sagi
  • 783
  • 1
  • 8
  • 17
  • Ok, i think i had a other issue. it seems to work now with Convert.toInt(e) and e.toString() dont know – Sagi Sep 14 '20 at 10:53
  • 1
    If you pass enum value as `Enum`, CLR will [box the value](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing). Use generic type to avoid boxing. – weichch Sep 14 '20 at 10:59

1 Answers1

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);
weichch
  • 9,306
  • 1
  • 13
  • 25
  • Just for reference: [Enumeration format strings](https://learn.microsoft.com/en-us/dotnet/standard/base-types/enumeration-format-strings) (feel free to use in answer) – Fildor Sep 14 '20 at 10:50
  • 3
    Alternative: `Console.WriteLine(Convert.ToInt32(e)); Console.WriteLine(e.ToString());` –  Sep 14 '20 at 10:59
  • `Convert.ToInt32(e)` will box the enum value, but it does remind me, because the type is constrained, we should just use `.ToString()`. – weichch Sep 14 '20 at 11:08