Programmer's Highway

VB.NET Tips and simple code

I'm very sorry for machine translation in English.

VB.NET How to use Enum

Definition of enum. The default type is Int32 Internally, the value is assigned from 0 in the order in which they were declared.

    Enum DayOfWeek
        Sunday
        Monday
        Tuesday
        Wednesday
        Thursday
        Friday
        Saturday
    End Enum

Declare the type or value of the internal. In the example below will be of type uint, value is allocated from one.

    Enum DayOfWeek As UInteger
        Sunday = 1
        Monday
        Tuesday
        Wednesday
        Thursday
        Friday
        Saturday
    End Enum

If you want to items such as drop-down list, To enumerate all the values in the Enum.GetValues method.

    For Each item In [Enum].GetValues(GetType(DayOfWeek))
        comboBox1.Items.Add(item.ToString())
    Next

If you want to convert enum value from a string, To callEnum.Parsemethod orEnum.TryParsemethod.

    ' Enum.Parse()
    Dim w As DayOfWeek = DirectCast([Enum].Parse(GetType(DayOfWeek), "Sunday"), DayOfWeek)
    
    ' Enum.TryParse()
    [Enum].TryParse(Of DayOfWeek)("Sunday", w)

If you take more than one value, treated as a "bit field" attribute to external [Flags].

    <Flags()>
    Enum DayOfWeek As Byte
        Sunday = 1
        Monday = 2
        Tuesday = 4
        Wednesday = 8
        Thursday = 16
        Friday = 32
        Saturday = 64
    End Enum

OR operator can specify more than one in. And, Is a comma-delimited output as below then ToString().

    Dim weekend As DayOfWeek = DayOfWeek.Sunday Or DayOfWeek.Saturday
    Console.WriteLine(weekend.ToString())        ' output: Sunday, Saturday

HasFlag method can Test the flags.

    Public Function IsWeekend(w As DayOfWeekAs Boolean
        Return w.HasFlag(DayOfWeek.Sunday Or DayOfWeek.Saturday)
    End Function
Visual Studio 2010 .NET Framework 4