Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting enum to int

Tags:

c#

enums

casting

I have the following enum

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

I then want to use this to compare to an integer variable that I have, like this:

if ( myValue == TESTENUM.Value1 )
{
}

But in order to do this test I have to cast the enum as follows (or presumably declare the integer as type enum):

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

Is there a way that I can tell the compiler that the enum is a series of integers, so that I don’t have to do this cast or redefine the variable?

like image 617
Paul Michaels Avatar asked Jun 22 '10 07:06

Paul Michaels


People also ask

Can I convert an enum to an int?

Overview. To convert an enum to int , we can: Typecast the enum value to int . Use the ToInt32 method of the Convert class.

Can enum be treated as int?

So the answer to “Can I treat an enum variable as an int in C17?” is no, as an object with enumerated type might be effectively a char or other integer type different from int .

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.


3 Answers

Keep in mind that casting the enum value in your context is exactly how you tell the compiler that "look here, I know this enum value to be of type int, so use it as such".

like image 25
PjL Avatar answered Sep 28 '22 12:09

PjL


No. You need to cast the enum value. If you don't want to cast, then consider using a class with constant int values:

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

However, there are some downsides to this; the lack of type safety being a big reason to use the enum.

like image 92
codekaizen Avatar answered Sep 28 '22 14:09

codekaizen


You can tell the enum that it contains integers:

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

However you have to still cast them manually,

like image 25
Juan Nunez Avatar answered Sep 28 '22 13:09

Juan Nunez