Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test if a bitwise enum contains any values from another bitwise enum in C#?

For instance. I have the following enum

[Flags]
public enum Stuff
{
   stuff1=1,
   stuff2=2,
   stuff3=4,
   stuff4=8
}

So I set mystuff to

mystuff = Stuff.stuff1|Stuff.stuff2;

then I set hisstuff to

hisstuff = Stuff.stuff2|Stuff.stuff3;

How do I now test if these overlap -ie hisstuff and mystuff both contain at least one of the same enum values?

And also if there are multiple ways to do it which is the most efficient? (This is for a game)

like image 828
coolblue2000 Avatar asked Oct 20 '12 12:10

coolblue2000


2 Answers

Simple:

if((x & y) != 0) {...}

This does a bitwise "and", then tests for any intersection.

like image 169
Marc Gravell Avatar answered Nov 02 '22 08:11

Marc Gravell


To get the values that are set in both values, you use the and (&) operator:

mystuff & hisstuff

This gives you a new value with only the overlapping values, in your example only Stuff.stuff2. To check if any of the values overlap, you check if it is non-zero:

if ((mystuff & hisstuff) != 0) ...
like image 11
Guffa Avatar answered Nov 02 '22 09:11

Guffa