Condividi tramite


FlagsAttribute Class

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Indicates that an enumeration can be treated as a bit field; that is, a set of flags.

Inheritance Hierarchy

System.Object
  System.Attribute
    System.FlagsAttribute

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

Syntax

'Declaration
<ComVisibleAttribute(True)> _
<AttributeUsageAttribute(AttributeTargets.Enum, Inherited := False)> _
Public Class FlagsAttribute _
    Inherits Attribute
[ComVisibleAttribute(true)]
[AttributeUsageAttribute(AttributeTargets.Enum, Inherited = false)]
public class FlagsAttribute : Attribute

The FlagsAttribute type exposes the following members.

Constructors

  Name Description
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 FlagsAttribute Initializes a new instance of the FlagsAttribute class.

Top

Methods

  Name Description
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Equals Infrastructure. Returns a value that indicates whether this instance is equal to a specified object. (Inherited from Attribute.)
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Finalize Allows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetHashCode Returns the hash code for this instance. (Inherited from Attribute.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetType Gets the Type of the current instance. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Match When overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Inherited from Attribute.)
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToString Returns a string that represents the current object. (Inherited from Object.)

Top

Remarks

Bit fields are generally used for lists of elements that might occur in combination, whereas enumeration constants are generally used for lists of mutually exclusive elements. Therefore, bit fields are designed to be combined with a bitwise OR operation to generate unnamed values, whereas enumerated constants are not. Languages vary in their use of bit fields compared to enumeration constants.

Attributes of the FlagsAttribute

AttributeUsageAttribute is applied to this class, and its Inherited property specifies false. This attribute can only be applied to enumerations.

Guidelines for FlagsAttribute and Enum

  • 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.

  • Consider creating an enumerated constant for commonly used flag combinations. For example, if you have an enumeration used for file I/O operations that contains the enumerated constants Read = 1 and Write = 2, consider creating the enumerated constant ReadWrite = Read OR Write, which combines the Read and Write flags. In addition, the bitwise OR operation used to combine the flags might be considered an advanced concept in some circumstances that should not be required for simple tasks.

  • Use caution if you define a negative number as a flag enumerated constant because many flag positions might be set to 1, which might make your code confusing and encourage coding errors.

  • A convenient way to test whether a flag is set in a numeric value is to perform a bitwise AND operation between the numeric value and the flag enumerated constant, which sets all bits in the numeric value to zero that do not correspond to the flag, then test whether the result of that operation is equal to the flag enumerated constant.

  • Use None as the name of the flag enumerated constant whose value is zero. You cannot use the None enumerated constant in a bitwise AND operation to test for a flag because the result is always zero. However, you can perform a logical, not a bitwise, comparison between the numeric value and the None enumerated constant to determine whether any bits in the numeric value are set.

    If you create a value enumeration instead of a flags enumeration, it is still worthwhile to create a None enumerated constant. The reason is that by default the memory used for the enumeration is initialized to zero by the common language runtime. Consequently, if you do not define a constant whose value is zero, the enumeration will contain an illegal value when it is created.

    If there is an obvious default case your application needs to represent, consider using an enumerated constant whose value is zero to represent the default. If there is no default case, consider using an enumerated constant whose value is zero that means the case that is not represented by any of the other enumerated constants.

  • Do not define an enumeration value solely to mirror the state of the enumeration itself. For example, do not define an enumerated constant that merely marks the end of the enumeration. If you need to determine the last value of the enumeration, check for that value explicitly. In addition, you can perform a range check for the first and last enumerated constant if all values within the range are valid.

  • Do not specify enumerated constants that are reserved for future use.

  • When you define a method or property that takes an enumerated constant as a value, consider validating the value. The reason is that you can cast a numeric value to the enumeration type even if that numeric value is not defined in the enumeration.

Examples

The following code example illustrates the use of the FlagsAttribute attribute and shows the effect on the ToString method of using FlagsAttribute on an Enum declaration.

' Example of the FlagsAttribute attribute.

Module Example

   ' Define an Enum without FlagsAttribute.
   Enum SingleHue As Short
      Black = 0
      Red = 1
      Green = 2
      Blue = 4
   End Enum

   ' Define an Enum with FlagsAttribute.
   <FlagsAttribute()> _
   Enum MultiHue As Short
      Black = 0
      Red = 1
      Green = 2
      Blue = 4
   End Enum

   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      outputBlock.Text &= _
          "This example of the FlagsAttribute attribute " & _
          vbCrLf & "generates the following output." & vbCrLf
      outputBlock.Text &= vbCrLf & _
          "All possible combinations of values of an " & _
          vbCrLf & "Enum without FlagsAttribute:" & vbCrLf & vbCrLf

      ' Display all possible combinations of values.
      Dim val As Integer
      For val = 0 To 8
         outputBlock.Text &= String.Format("{0,3} - {1}", _
             val, CType(val, SingleHue).ToString()) & vbCrLf
      Next val

      outputBlock.Text &= String.Format(vbCrLf & _
          "All possible combinations of values of an " & _
          vbCrLf & "Enum with FlagsAttribute:" & vbCrLf) & vbCrLf

      ' Display all possible combinations of values.
      ' Also display an invalid value.
      For val = 0 To 8
         outputBlock.Text &= String.Format("{0,3} - {1}", _
             val, CType(val, MultiHue).ToString()) & vbCrLf
      Next val
   End Sub
End Module

' This example of the FlagsAttribute attribute
' generates the following output.
' 
' All possible combinations of values of an
' Enum without FlagsAttribute:
' 
'   0 - Black
'   1 - Red
'   2 - Green
'   3 - 3
'   4 - Blue
'   5 - 5
'   6 - 6
'   7 - 7
'   8 - 8
' 
' All possible combinations of values of an
' Enum with FlagsAttribute:
' 
'   0 - Black
'   1 - Red
'   2 - Green
'   3 - Red, Green
'   4 - Blue
'   5 - Red, Blue
'   6 - Green, Blue
'   7 - Red, Green, Blue
'   8 - 8
// Example of the FlagsAttribute attribute.
using System;

class Example
{
   // Define an Enum without FlagsAttribute.
   enum SingleHue : short
   {
      Black = 0,
      Red = 1,
      Green = 2,
      Blue = 4
   };

   // Define an Enum with FlagsAttribute.
   [FlagsAttribute]
   enum MultiHue : short
   {
      Black = 0,
      Red = 1,
      Green = 2,
      Blue = 4
   };

   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      outputBlock.Text +=
          "This example of the FlagsAttribute attribute \n" +
          "generates the following output." + "\n";
      outputBlock.Text +=
          "\nAll possible combinations of values of an \n" +
          "Enum without FlagsAttribute:\n" + "\n";

      // Display all possible combinations of values.
      for (int val = 0; val <= 8; val++)
         outputBlock.Text += String.Format("{0,3} - {1}",
             val, ((SingleHue)val).ToString()) + "\n";

      outputBlock.Text += String.Format(
          "\nAll possible combinations of values of an \n" +
          "Enum with FlagsAttribute:\n") + "\n";

      // Display all possible combinations of values.
      // Also display an invalid value.
      for (int val = 0; val <= 8; val++)
         outputBlock.Text += String.Format("{0,3} - {1}",
             val, ((MultiHue)val).ToString()) + "\n";
   }
}

/*
This example of the FlagsAttribute attribute
generates the following output.

All possible combinations of values of an
Enum without FlagsAttribute:

  0 - Black
  1 - Red
  2 - Green
  3 - 3
  4 - Blue
  5 - 5
  6 - 6
  7 - 7
  8 - 8

All possible combinations of values of an
Enum with FlagsAttribute:

  0 - Black
  1 - Red
  2 - Green
  3 - Red, Green
  4 - Blue
  5 - Red, Blue
  6 - Green, Blue
  7 - Red, Green, Blue
  8 - 8
*/

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference