Home
VB.NET
Enum Flags Attribute Example
This page was last reviewed on Aug 1, 2024.
Dot Net Perls
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.
Enum
Attribute
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.
Example. 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.
Step 1 We create a new instance of the FileAttributes Enum. We use an "Or" expression to set two flags at once.
Bitwise XOR
Step 2 We use the HasFlag Function to test if the Current attribute is set on FileAttributes.
If
Step 3 To see if a flag is not set, we can use Not with the HasFlag Function.
Step 4 It is possible to remove a flag that has been set by using the VB.NET And Not operators.
Step 5 By calling 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 Module
SET CACHED AND CURRENT FLAGS ... File is current ... File is not obsolete REMOVE CURRENT FLAG ... File is not current
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 1, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.