Brijesh Patel
Brijesh Patel

Reputation: 2958

Define String ENUM in VB.Net

I am using Window Application for my project. There is situation where i need to define string enum and using it in my project.

i.e.

Dim PersonalInfo As String = "Personal Info"
Dim Contanct As String = "Personal Contanct"

    Public Enum Test
        PersonalInfo
        Contanct
    End Enum

Now i want value of that variable PersonalInfo and Contract as "Personal Info" and "Personal Contanct".

How can i get this value using ENUM? or anyother way to do it.

Thanks in advance...

Upvotes: 37

Views: 85015

Answers (7)

Zeek2
Zeek2

Reputation: 424

This technique from Microsoft - "How to: Determine the String Associated with an Enumeration Value (Visual Basic)" - will be useful in some situations (it didn't help with mine unfortunately though :( ). Microsoft's example:

VB:

Public Enum flavorEnum
    salty
    sweet
    sour
    bitter
End Enum

Private Sub TestMethod()
    MsgBox("The strings in the flavorEnum are:")
    Dim i As String
    For Each i In [Enum].GetNames(GetType(flavorEnum))
        MsgBox(i)
    Next
End Sub

Upvotes: 1

SteveCinq
SteveCinq

Reputation: 1973

If all you want to do is display the enums in a list or combo, you can use tagging such as

Private Enum MyEnum
    Select_an_option___
    __ACCOUNTS__
    Invoices0
    Review_Invoice
    __MEETINGS__
    Scheduled_Meetings0
    Open_Meeting
    Cancelled_Meetings0
    Current_Meetings0
End Enum

Then pull the MyEnum into a string and use Replace (or Regex) to replace the tags: "___" with "...", "__" with "**", "_" with " ", and remove trailing numbers. Then repack it up into an array and dump it into a combobox which will look like:

Select an option...
**ACCOUNTS**
Invoices
Review Invoice
**MEETINGS**
Scheduled Meetings
Open Meeting
Cancelled Meetings
Current Meetings

(You can use the numbers to, say, disable a text field for inputting an invoice number or meeting room. In the example, Review Invoice and Open Meeting might be expecting additional input so a text box might be enabled for those selections.)

When you parse the selected combo item, the enumeration will work as expected but you only really need to add a single line of code - the text replacement - to get the combo to look as you wish.

(The explanation is about 10 times as involved as the actual solution!)

Upvotes: 2

Slai
Slai

Reputation: 22896

For non-integer values, Const in a Structure (or Class) can be used instead:

Structure Test
    Const PersonalInfo = "Personal Info"
    Const Contanct = "Personal Contanct"
End Structure

or in a Module for direct access without the Test. part:

Module Test
    Public Const PersonalInfo = "Personal Info"
    Public Const Contanct = "Personal Contanct"
End Module

In some cases, the variable name can be used as a value:

Enum Test
    Personal_Info
    Personal_Contanct
End Enum

Dim PersonalInfo As String = Test.Personal_Info.ToString.Replace("_"c, " "c)

' or in Visual Studio 2015 and newer:
Dim Contanct As String = NameOf(Test.Personal_Contanct).Replace("_"c, " "c)

Upvotes: 59

Denis
Denis

Reputation: 12087

How about using Tagging. Something like:

Public Enum MyEnum
<StringValue("Personal Contact")>Contact
<StringValue("My PersonalInfo")>PersonalInfo
End Enum

You would have to write the StringValue attribute as:

Public Class StringValueAttribute
    Inherits Attribute

    Public Property Value As String
    Public Sub New(ByVal val As String)
        Value = val
    End Sub

End Class

To get it out:

 Public Function GetEnumByStringValueAttribute(value As String, enumType As Type) As Object
    For Each val As [Enum] In [Enum].GetValues(enumType)
        Dim fi As FieldInfo = enumType.GetField(val.ToString())
        Dim attributes As StringValueAttribute() = DirectCast(fi.GetCustomAttributes(GetType(StringValueAttribute), False), StringValueAttribute())
        Dim attr As StringValueAttribute = attributes(0)
        If attr.Value = value Then
            Return val
        End If
    Next
    Throw New ArgumentException("The value '" & value & "' is not supported.")
End Function

Public Function GetEnumByStringValueAttribute(Of YourEnumType)(value As String) As YourEnumType
    Return CType(GetEnumByStringValueAttribute(value, GetType(YourEnumType)), YourEnumType)
End Function

And then a call to get the Enum (using string attribute):

Dim mEnum as MyEnum = GetEnumByStringValueAttribute(Of MyEnum)("Personal Contact")

To get the "Attribute" value out (removed handling 'Nothing' for clarity):

  Public Function GetEnumValue(Of YourEnumType)(p As YourEnumType) As String
        Return DirectCast(Attribute.GetCustomAttribute(ForValue(p), GetType(StringValueAttribute)), StringValueAttribute).Value
  End Function

  Private Function ForValue(Of YourEnumType)(p As YourEnumType) As MemberInfo
        Return GetType(YourEnumType).GetField([Enum].GetName(GetType(YourEnumType), p))
  End Function

And the call to get the string attribute (using Enum):

Dim strValue as String = GetEnumValue(Of MyEnum)(MyEnum.Contact)

Upvotes: 10

sloth
sloth

Reputation: 101162

You could just create a new type

''' <completionlist cref="Test"/>
Class Test

    Private Key As String

    Public Shared ReadOnly Contact  As Test = New Test("Personal Contanct")
    Public Shared ReadOnly PersonalInfo As Test = New Test("Personal Info")

    Private Sub New(key as String)
        Me.Key = key
    End Sub

    Public Overrides Function ToString() As String
        Return Me.Key
    End Function
End Class

and when you use it, it kinda looks like an enum:

Sub Main

    DoSomething(Test.Contact)
    DoSomething(Test.PersonalInfo)

End Sub

Sub DoSomething(test As Test)
    Console.WriteLine(test.ToString())
End Sub

output:

Personal Contanct
Personal Info

Upvotes: 27

Rob Heijligers
Rob Heijligers

Reputation: 173

I know this is an old post put I found a nice solution that worth sharing:

''' <summary>
''' Gives acces to strings paths that are used often in the application
''' </summary>
Public NotInheritable Class Link        
    Public Const lrAutoSpeed As String          = "scVirtualMaster<.lrAutoSpeed>"
    Public Const eSimpleStatus As String        = "scMachineControl<.eSimpleStatus>"
    Public Const xLivebitHMI As String          = "scMachineControl<.xLivebitHMI>"      
    Public Const xChangeCycleActive As String   = "scMachineControl<.xChangeCycleActive>"

End Class

Usage:

'Can be anywhere in you applicaiton:
Link.xChangeCycleActive

This prevents unwanted extra coding, it's easy to maintain and I think this minimizes extra processor overhead.

Also visual studio shows the string attributes right after you type "Link" just like if it is a regular Enum

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1503769

How can i get this value using ENUM? or anyother way to do it.

There are three common ways of mapping enum values to strings:

  • Use a Dictionary(Of YourEnumType, String)
  • Decorate the enum values with attributes (e.g. DescriptionAttribute) and fetch them with reflection
  • Use a Switch statement

The first of these options is probably the simplest, in my view.

Upvotes: 5

Related Questions