coolblue2000
coolblue2000

Reputation: 4888

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)

Upvotes: 22

Views: 6575

Answers (2)

Guffa
Guffa

Reputation: 700252

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) ...

Upvotes: 11

Marc Gravell
Marc Gravell

Reputation: 1062650

Simple:

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

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

Upvotes: 28

Related Questions