Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare enum and int values?

Tags:

c#

.net

enums

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.

like image 930
Budda Avatar asked Mar 11 '11 17:03

Budda


1 Answers

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?

like image 168
Melllvar Avatar answered Sep 23 '22 12:09

Melllvar