FlagsAttribute why?

What is the difference between the code below

' no Flags'
Public Enum MyEnum
  Monday = 1
  Tuesday = 2
  Wednesday = 4
  Thursday = 8
End Enum

and

<Flags()> _ 
Public Enum MyEnum
  Monday = 1
  Tuesday = 2
  Wednesday = 4
  Thursday = 8
End Enum

I do

Dim days As MyEnum = MyEnum.Monday Or MyEnum.Tuesday Or MyEnum.Wednesday 

If (days And MyEnum.Tuesday) = MyEnum.Tuesday Then
  Console.WriteLine("Tuesday OK") ' here'
Else
  Console.WriteLine("Tuesday NOK")
End If

If (days And MyEnum.Thursday ) = MyEnum.Thursday Then
  Console.WriteLine("Thursday OK")
Else
  Console.WriteLine("Thursday NOK") ' here'
End If

and get the same result in both cases (with or without FlagAttribute).

+3
source share
5 answers

Basically, it tells the CLR that enumeration values ​​can be combined. Without this attribute, combining values ​​will result in an unknown value (but it will still be valid). The combination is correctly interpreted with the attribute

Without attributes Flags:

' Gives "Monday, Tuesday" '
Dim s As String = (MyEnum.Monday Or MyEnum.Tuesday).ToString() 

Without attributes Flags:

' Gives "3" '
Dim s As String = (MyEnum.Monday Or MyEnum.Tuesday).ToString() 
+5
source

This only affects ToString ()

+2
source

VB, . , , . , - :

enum Format
{
  Bold = 1,
  Italic = 2,
  Underlined = 4
}

Then you can specify Formathow:

Format format = Format.Bold | Format.Italic;
// Then a check to see if the format is bold or italic should both pass.

Now it is both bold and italic (equal to 3). However, you cannot set this without the flags attribute. This prevents the exclusion of options that exclude mutual exclusion. To do this without flags, you will need to:

enum Format
{
  Bold,
  BoldUnderlined,
  BoldItalic,
  BoldUnderlinedItalic,  
  Underlined,  
  Italic,
  ItalicUnderlined
}

Not as good as nice.

0
source

See Thomas Levesque's answer. For example, you can:

switch (test.day)
{
    case MyEnum.Monday:
    {
        //something when its monday
    }
    break;
    case MyEnum.Tuesday:
    {
        //something when its tuesday
    }
    break;
    case MyEnum.Monday | MyEnum.Tuesday:
    {
        //something when its monday and tuesday (oh the irony)
    }
    break;
}       
-1
source

Source: https://habr.com/ru/post/1732495/


All Articles