Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum.GetName vs Enum.ToString

For this enumeration,

Enum MyEnum
    Value
End Enum

there are two methods to get the name representation Value of MyEnum.Value:

[Enum].GetName(GetType(MyEnum), MyEnum.Value) ' aka Enum.GetName

and

Dim a As MyEnum = MyEnum.Value
a.ToString ' aka Enum.ToString

What are their pros and cons? And which is better after all?

PS: There is one answer for java but this is .NET which may have different functionality.

like image 710
Happypig375 Avatar asked Oct 19 '22 07:10

Happypig375


1 Answers

Here are some examples of what can be done using this enum, note the usage of the flags attribute.

    <Flags>
   Public Enum bit As Short
        none = 0
        s0 = 1 << 0
        s1 = 1 << 1
        s2 = 1 << 2
        s3 = 1 << 3
        s4 = 1 << 4
        s5 = 1 << 5
        s6 = 1 << 6
        s7 = 1 << 7
        s8 = 1 << 8
        s9 = 1 << 9
        s10 = 1 << 10
        s11 = 1 << 11
        s12 = 1 << 12
        s13 = 1 << 13
        s14 = 1 << 14
        all = -1
    End Enum

and this code

    Dim s As String = bit.s13.ToString
    s = (bit.s10 Or bit.s11).ToString

    Dim foo() As String
    foo = [Enum].GetNames(GetType(bit))

    For Each s As String In foo
        Debug.WriteLine(s)
    Next

    Dim test As bit = bit.s1 Or bit.s3 Or bit.s5
    Debug.WriteLine(test.ToString)
    Debug.WriteLine(CShort(test).ToString)

    test = test Or CType([Enum].Parse(GetType(bit), "s14"), bit)
    Debug.WriteLine(test.ToString)
like image 192
dbasnett Avatar answered Oct 30 '22 21:10

dbasnett