views:

75

answers:

4

In standard MSN code, there's a line on a ListView - Ownerdraw - DrawItem :

if ((e.State & ListViewItemStates.Selected) != 0)
{
    //Draw the selected background
}

Apparently it does a bitwise comparison for the state ?? Why bitwise ? The following doesn't work:

if (e.State == ListViewItemStates.Selected)
{
    //Doesn't work ??
}

Why doesn't that comparison work ? It's just a standard Enum ?? I'm a bit bedaffled ..

+9  A: 

It's not a standard Enum - it's decorated with the FlagsAttribute, making it a bitmask. See MSDN FlagsAttribute for details.

The first example checks whether any of the flags is set, as you have rightly interpreted. Flags are generally combined using the | operator (though + and ^ are also safe for a properly specified attribute with no overlaps).

David M
Ahhh ok I understand now. e.State could be different values at the same time, for example it could be both ListViewItemStates.Selected and ListViewItemStates.Hot ... therefore a one on one comparison (==) is not appropriate ... Thanks!!
Run CMD
Yes, exactly right.
David M
+4  A: 

It's possible to use Enumeration Types as Bit Flags.

dtb
+1  A: 

The value of state is a flag enum - this means different bits in it mean different things and they can be combined to tell you multiple things about the state. For example

[Flags]
public enum States
{
    Selected = 1;
    OnScreen = 2;
    Purple = 4;
} 

So if you want to see if something is selected you can't just compare it to selected (see if it has an int value of 1) because it could be both selected and onscreen (and it would have an int value of 3). By doing a bitwise comparison you are checking that the Selected flag is set ignoring the value of the other flags.

Martin Harris
+1  A: 

ListViewItemStates is a "Flag" enumeration : a variable of ListViewItemStates can be a combinaison of values. Ex : Focuses and Checked

If you use an equality like e.State == ListViewItemStates.Selected to determine if an item is selected, you will be able to detect the case where the value is "Selected" only, but you will miss the case where the value is a composition of states.

The bitwise operation let you test for a value independently.

Hope it helps

Cédric Rup