views:

224

answers:

2

Just an academical question: Is it possible to avoid int casting when comparing Enum to int?

int i = 0;
if(i == (int)MyEnum.Whatever)
{
} 

I would like to overload == operator in such a manner:

public static MyEnum operator ==(int lhs, MyEnum rhs)
{}

Thanks for reading ;-)

A: 

You can't. See this similar question. As suggested in that question, you could define an extension method to do the comparison, in order to get rid of the repeated casts.

driis
I saw that question, but ChrisHDog in that question was asking about overloading operator for two enums, so I had my hopes ;-) But thanks.
Michal Krawiec
A: 

No, not possible. the question is - why do you compare to in at all?

TomTom
Because I have int Id from database.
Michal Krawiec
Comparing enums to int is also very common when talking to an embedded application, or a field bus system, or something.
OregonGhost
Yeah, bit Id#s from a database dont really map to enum ;) Normally. Ints in embedded makes sense. I would cast to enum asap, then go on working comparing enums. Get rid of the "lower level" representation asap.
TomTom
IMHO If you consider dogs table and BreedId in every row than in app it is very useful to have enum 'GoldenRetriever' = 1, etc.
Michal Krawiec