tags:

views:

181

answers:

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?

+1  A: 

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

Pavel Radzivilovsky
+2  A: 

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,

Juan Nunez
You still need to cast.
codekaizen
All enums are int by default.
Xavier Poinas
you dont have to provide :Int as it is by default.
Chinjoo
+7  A: 

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.

codekaizen
Thanks for the downvote. Just feel like losing points today, or do you have some specific reason for doing so that you'd like to share?
codekaizen
Is there a way to know who downvoted?
jmoreno
+1 Good answer. Not only did you provide the answer "You need to cast the enum value", but you also provided an alternative that might be appropriate for @pm_2. Whoever downvoted you should provide a reason. Perhaps it was the use of the class name TestEnum for something that is not an enum. We may never know. Whatever, it wasn't worth a downvote.
Daniel Dyson
@Daniel - good point, maybe it's the bad class name. There, I fixed it!
codekaizen
@jmoreno - No, at least, not at my lowly level of points. It's probably for the best!
codekaizen
A: 

It's uglier IMO, but you could compare the string representation, like so:

if ( myValue.ToString() == TESTENUM.Value1.ToString("d") )
{
}

It also looks like:

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

would work

jmoreno
No, apart from being ugly (as you already said), the TESTENUM.Value1.ToString() would result in "Value1", not "1".
Hans Kesting
Then you'd just end up comparing, say, "1" == "Value1" which wouldn't be correct either. In any case, comparing the string representations is an awful solution (especially as you're not passing a culture to the `ToString` methods, meaning that the semantics could vary by environment).
Greg Beech
@Hans, yeah, I left off the format specifier: TESTENUM.Value1.ToString("d")
jmoreno
+1  A: 

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

PjL