0

If you have a [Flags] enum instance called typeToAdjust, and you want to see if it's equal to clientType, is there any point doing this?

 (clientType & (int)typeToAdjust) == (int)typeToAdjust

Doesn't this do the same?:

clientType == (int)typeToAdjust
David Klempfner
  • 8,700
  • 20
  • 73
  • 153
  • Did you mistype the second statement? Did you meant `&` instead of `==` ? – Mark Lakata Sep 23 '15 at 02:03
  • 2
    possible duplicate of [How to Compare Flags in C#?](http://stackoverflow.com/questions/40211/how-to-compare-flags-in-c) – Metro Smurf Sep 23 '15 at 02:03
  • not really an answer to that specific question ; but from FW4.5 you can use the [HasFlag](https://msdn.microsoft.com/en-us/library/system.enum.hasflag%28v=vs.110%29.aspx) method to simplify things ; it will do exactly that – Sehnsucht Sep 23 '15 at 02:15

4 Answers4

1

If you have more than one flag set in clientType, then you must do the first one, although you could do this also:

(clientType & (int)typeToAdjust) != 0 

You seem to have missed the whole idea of [Flags] which allows one or more bits to be set.

Mark Lakata
  • 19,989
  • 5
  • 106
  • 123
0

Yes but the point of having a flags enum is so you can combine them so

   typeToAdjust = type1 
   clientType = type1 | type2
   (clientType & (int)typeToAdjust) == (int)typeToAdjust // true
   clientType == (int)typeToAdjust // false
Mark
  • 2,926
  • 3
  • 28
  • 31
0

The two statements are different, but the second is the one that actually tests equality. If clientType has a superset of the bits set in typeToAdjust, then the first expression will evaluate to true since (clientType & (int)typeToAdjust) just evaluates to typeToAdjust. By superset, I mean that all of the bits set in typetoAdjust are set in clientType, but maybe some additional bits as well.

Jeremy West
  • 11,495
  • 1
  • 18
  • 25
0

(clientType & (int)typeToAdjust) == (int)typeToAdjust

and clientType == (int)typeToAdjust

Are not the same

Take clientType = 3 and typeToAdjust = 1

clientType & (int)typeToAdjust = 1 = typeToAdjust but clientType != (int)typeToAdjust

Razack
  • 1,826
  • 2
  • 16
  • 37