5

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?

0

4 Answers 4

12

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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,

2 Comments

All enums are int by default.
you dont have to provide :Int as it is by default.
2

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".

Comments

1

No there isn't (unlike C++), and for a good reason of type safety.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.