Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this statement mean in C#?

What does if ((a & b) == b) mean in the following code block?

if ((e.Modifiers & Keys.Shift) == Keys.Shift)
{
    lbl.Text += "\n" + "Shift was held down.";
}

Why is it not like this?

if (e.Modifiers == Keys.Shift)
{
    lbl.Text += "\n" + "Shift was held down.";
}
like image 503
Mohammad Avatar asked Apr 17 '13 15:04

Mohammad


1 Answers

If you take a look Keys enum, this is flag enum with [FlagsAttribute] attribute.

Use the FlagsAttribute custom attribute for an enumeration only if a bitwise operation (AND, OR, EXCLUSIVE OR) is to be performed on a numeric value.

Define enumeration constants in powers of two, that is, 1, 2, 4, 8, and so on. This means the individual flags in combined enumeration constants do not overlap.

So e.Modifiers might be a combination of more than one enum:

e.Modifiers = Keys.Shift | Keys.Cancel | Keys.Enter

Just very simple assumption to explain the concept:

Keys.Shift  : 001 (1)
Keys.Cancel : 010 (2)
Keys.Enter  : 100 (4)

So:

e.Modifiers = Keys.Shift | Keys.Cancel | Keys.Enter equal 001 | 010 | 100 = 111

And the condition:

    e.Modifiers & Keys.Shift equal 111 & 001 = 001

it means:

 e.Modifiers & Keys.Shift == Keys.Shift

if e.Modifiers does not contains Keys.Shift:

e.Modifiers = Keys.Cancel | Keys.Enter (110)

So the result will be:

e.Modifiers & Keys.Shift equals 110 & 001 = 000 (is not Keys.Shift)

To sump up, this condition checks whether e.Modifiers contains Keys.Shift or not

like image 188
cuongle Avatar answered Oct 14 '22 09:10

cuongle