How to compare enum and int values?

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?


This can help.

var constant = 1;
if(constant == (int)MyEnum.Valid1){
......
}

They are exactly the same. Displaying the generated IL using the Debug, Windows, Disassembly (Ctrl-Alt-D) gives you:

MyEnum e1 = MyEnum.Value1;
00260834  mov         dword ptr [ebp-3Ch],1  
int i1 = 2;
0026083B  mov         dword ptr [ebp-40h],2  

// Is there any difference how to compare enumEration values with integers?
if (e1 == (MyEnum) i1) 
00260842  mov         eax,dword ptr [ebp-3Ch]  
00260845  cmp         eax,dword ptr [ebp-40h]  
00260848  sete        al  
0026084B  movzx       eax,al  
0026084E  mov         dword ptr [ebp-44h],eax  
00260851  cmp         dword ptr [ebp-44h],0  
00260855  je          00260858  
; // 1st
00260857  nop  

if ((int)e1 == i1)
00260858  mov         eax,dword ptr [ebp-3Ch]  
0026085B  cmp         eax,dword ptr [ebp-40h]  
0026085E  sete        al  
00260861  movzx       eax,al  
00260864  mov         dword ptr [ebp-48h],eax  
00260867  cmp         dword ptr [ebp-48h],0  
0026086B  je          0026086E  
; // 2nd
0026086D  nop  

I would recommend casting the int to the representative enum value when you read it from the database. This will greatly improve the readability of your code.

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

MyEnum dbValue = ReadEnumFromDB();
if(dbValue == MyEnum.Invalid)
{
   ...
}