Convert enum to int

I have the following listing

public enum TESTENUM
{
    Value1 = 1,
    Value2 = 2
}

Then I want to use this to compare with the integer variable that I have:

if ( myValue == TESTENUM.Value1 )
{
}

But for this test, I have to do the enumeration as follows (or presumably declare an integer as an enumeration of type):

if ( myValue == (int) TESTENUM.Value1 )
{
}

Is there a way I can tell the compiler that an enumeration is a series of integers, so I don't need to do this casting or overriding a variable?

+5
source share
4 answers

No. You need to specify the value of the enumeration. If you do not want to throw, then consider using a class with constant int values:

class static EnumLikeClass
{
    public const int Value1 = 1;
    public const int Value2 = 2;
}

; enum.

+12

, :

public enum TESTENUM: int
{
    Value1 = 1,
    Value2 = 2
}

,

+2

Keep in mind that a great enumeration value in your context is exactly how you tell the compiler that “look here, I know that this enum value is of type int, so use it as such.”

+2
source

No, no (unlike C ++) and for the good reason of type safety.

+1
source

All Articles