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?
Overview. To convert an enum to int , we can: Typecast the enum value to int . Use the ToInt32 method of the Convert class.
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 .
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.
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".
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
.
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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With