Enum Flags comparison

C

Christian.Wall

Hello,

I've got the following enum:

[Flags]
public enum MyStates
{
None = 0
Saved = 1
New = 2
Changed = 4
Deleted = 8
Moved = 16
}

....

Now I create two variables:

MyStates aValue = MyStates.Changed | MyStates.Moved | MyStates.New
MyStates bValue = MyStates.Changed | MyStates.New

Now i want to check if the values in bValue included in aValue (this
must be true)

But if i create a variable, let's call her cValue:
MyStates cValue = MyStates.Changed | MyStates.Saved

In this case cValue is not included in aValue... But my If statement
returns > 1 when I compare aValue and cValue:

if ( (IstWert & SollWert) > 0)
{
DoSomeThing();
}

Can somebody tell me, how to solve this problem?

Thanks, Chris
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

You should not include a value for 0 , if you want to check for it , how do
you know if it was None ?
 
M

Michael Bray

You should not include a value for 0 , if you want to check for it ,
how do you know if it was None ?

I disagree... including a value for 0 is quite useful.

You can check for it very simply:

MyStates state = MyStates.None;
if (state == MyStates.None) { ... }

Now obviously, this isn't the general way you would check for the non-zero
flags, which I usually do like this (is there a better way??):

if ((state & MyStates.Saved) == MyStates.Saved) { ... }

As for the OP question, Chris, you shouldn't check if the result is > 0,
you should check one of:

if (aValue & cValue == aValue) - then aValue is a subset of cValue
if (aValue & cValue == cValue) - then cValue is a subset of aValue

if either one doesn't evaluate, but the result > 0, then it means that they
have some common elements, but some different elements as well (this is the
case you are seeing currently.)

-mdb
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top