Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET enum.HasFlag() bug?

I'm using the following .NET 4.5.2 code:

if (this.ContainsFocus && keyData == (Keys.Tab|Keys.Shift))
{ ... }

Why is the expression true when ContainsFocus (bool = true) and keyData (System.Windows.Forms.Keys) is Keys.O | Keys.Shift?

As you can see the breakpoint is hit:

breakpointscreenshot

with this values:

watchscreenshot

A workaround for this bug (?!) is:

if (this.ContainsFocus && (int)keyData == (int)(Keys.Tab|Keys.Shift))
{ ... }
like image 430
CrazyTea Avatar asked Jul 30 '26 13:07

CrazyTea


2 Answers

No, HasFlag does not have a bug. Unfortunately, the .NET FlagsAttribute is all or nothing and System.Windows.Forms.Keys is defined in such a way that only Keys.Modifiers may be used as flags.

From https://msdn.microsoft.com/en-us/library/system.windows.forms.keys%28v=vs.110%29.aspx

The Keys class contains constants for processing keyboard input. The members of the Keys enumeration consist of a key code and a set of modifiers combined into a single integer value. In the Win32 application programming interface (API) a key value has two halves, with the high-order bits containing the key code (which is the same as a Windows virtual key code), and the low-order bits representing key modifiers such as the SHIFT, CONTROL, and ALT keys.

As a result, you can check any of the modifiers (Keys.Shift, Keys.Alt, Keys.Control) with HasFlag, but nothing else.

like image 63
jmc Avatar answered Aug 02 '26 02:08

jmc


This is not a bug of HasFlag, it is how it work.
Suppose we have the following values:

var a = (Keys.Tab | Keys.Shift);
var b = (Keys.O | Keys.Shift);

Now we analyze the bits of these values (when we cast them to integers):

a: 10000000001000001
b: 10000000001001111

If we call a.HasFlag(b) we get false because not every 1-bit from b is a 1 in a too. But if we call b.HasFlag(a) we get true because every 1-bit of a is set in b too.

That's why you need to compare the values with a==b or with a.HasFlag(b) && b.HasFlag(a). Then it will work properly.

like image 39
Koopakiller Avatar answered Aug 02 '26 03:08

Koopakiller