Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

enum MyEnum
{
    Invalid=0,
    Value1=1,
    Value1=2,
}

void main ()
{
    MyEnum e1 = MyEnum.Value1;
    int i1 = 2;

    // Is there any difference how to compare enumEration values with integers?
    if ( e1==(MyEnum)i1 )... // 1st

    if ( (int)e1==i1 )... // 2nd

In each of mentioned cases we have convertion of enum to int or int to enum.

Is there any difference in these conversions (performance, any other)? Or they are exactly the same?

Thanks.

P.S. In current example I compare to 'magic number' but in real application I am getting data from integer field from DB.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
534 views
Welcome To Ask or Share your Answers For Others

1 Answer

It doesn't matter which you use, they will perform identically. If there is no enum for an integer value, .net creates one at runtime. There can be no exceptions.

However, Xichen Li is correct - why would you want to compare an enum against an integer value?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...