Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the better way to compare Flags Enum?

Tags:

c#

Normally when comparing flag enums I use the following format:

(value & flag) == flag;

But sometimes I come across this:

(value & flag) != 0;

Just wondering which is the better to use, or does it come down to personal preference?

like image 654
Ɖiamond ǤeezeƦ Avatar asked Nov 26 '12 15:11

Ɖiamond ǤeezeƦ


2 Answers

if you are using .net 4 or higher use Enum.HasFlag instead

In fact this method uses first way of checking, but provide more clear way to check flags

like image 65
Arsen Mkrtchyan Avatar answered Sep 21 '22 07:09

Arsen Mkrtchyan


So long as flag is a one-bit flag, they are equivalent. If flag has multiple bits,

(value & flag) == flag;

is a logical AND (ALL bits must match) while

(value & flag) != 0;

is a logical OR (ANY of the bits must match).

like image 31
D Stanley Avatar answered Sep 18 '22 07:09

D Stanley