Flags
, Enum
Sometimes an Enum
may have multiple values set at the same time: in VB.NET, the Flags
attribute can help for this purpose. We can set, and remove, individual flags.
With the HasFlag
function, we can determine if a flag is set. With bitwise operators like Or and And, we can set (and remove) flags on the Enum
instance.
This VB.NET program uses a custom FileAttributes
Enum
and sets flags on it. Notice how the enum
uses powers of 2 for the values—this enables flags to be set without issues.
FileAttributes
Enum
. We use an "Or" expression to set two flags at once.HasFlag
Function to test if the Current attribute is set on FileAttributes
.HasFlag
Function.HasFlag
again, after the enum
value was modified, we can see that it correctly tests the presence of a flag.<Flags> Enum FileAttributes None = 0 Cached = 1 Current = 2 Obsolete = 4 End Enum Module Module1 Sub Main() ' Step 1: new enum instance. Console.WriteLine("SET CACHED AND CURRENT FLAGS") Dim attributes As FileAttributes = FileAttributes.Cached Or FileAttributes.Current ' Step 2: check Current flag. If attributes.HasFlag(FileAttributes.Current) Console.WriteLine("... File is current") End If ' Step 3: check Obsolete flag. If Not attributes.HasFlag(FileAttributes.Obsolete) Console.WriteLine("... File is not obsolete") End If ' Step 4: remove Current flag from instance. Console.WriteLine("REMOVE CURRENT FLAG") attributes = attributes And Not FileAttributes.Current ' Step 5: check Current flag again. If Not attributes.HasFlag(FileAttributes.Current) Console.WriteLine("... File is not current") End If End Sub End ModuleSET CACHED AND CURRENT FLAGS ... File is current ... File is not obsolete REMOVE CURRENT FLAG ... File is not current
With Enum
and the Flags
attribute, we can set multiple enum
values at the same time. The Flags
attribute works like a "bit flag" where each bit represents a boolean value.