Click here to Skip to main content
15,881,757 members
Articles / Programming Languages / Visual Basic

String Enumerations in VB.NET

Rate me:
Please Sign up or sign in to vote.
2.15/5 (6 votes)
4 May 2009BSD1 min read 58.6K   18   25
Fully compatible enumeration using strings in VB.NET.

Introduction

This class allows strings to be used as enumerations. It is fully compatible with strings, including easy casting to a string, upcasting from strings, concatenation, and compatible with strings using the = operator. Developers will be able to code against this class as if it were a normal enumeration - without any special handling required.

This StringEnumeration class allows you to bridge any real-world string constants with an acceptable .NET enumeration you can use throughout your code.

Scenarios for using this class - When an enumeration must contain:

  • Global Unique Identifiers (GUIDs)
  • Strings that include spaces
  • Strings with special characters or that begin with a number
  • Scalar/Mixed types (strings, numbers, etc.)

Background

.NET enumerations do not support strings out-of-the-box. This class fixes this limitation.

Using the Code

Creating a String Enumeration

Using the class is very simple, just inherit from StringEnumeration and call its constructor. Here is an example:

VB
Public NotInheritable Class ProductType
    Inherits StringEnumeration(of ProductType)

    Public Shared ReadOnly FifthWheels As New ProductType("Fifth Wheels")
    Public Shared ReadOnly MotorHomes As New ProductType("Motor Homes")
    Public Shared ReadOnly TentCampers As New ProductType("Tent Campers")
    Public Shared ReadOnly TravelTrailers As New ProductType("Travel Trailers")
    Public Shared ReadOnly TruckCampers As New ProductType("Truck Campers")

    Private Sub New(ByVal StringConstant As String)
        MyBase.New(StringConstant)
    End Sub
End Class

Passing as Arguments

Notice how ProductType can now be used as a type being passed to a method. It can also be easily used in Select Case statements, as a normal enumeration can be.

VB
Public Sub SomeMethod(ByVal myProductType As ProductType)
    Select Case myProductType
        Case ProductType.FifthWheels
        Case ProductType.MotorHomes
        Case ProductType.TentCampers
        Case ProductType.TravelTrailers
        Case ProductType.TruckCampers
    End Select
End Sub

UpCasting

Strings can also be transparently upcast to your StringEnumeration.

VB
Public Sub SomeMethod(ByVal myProductType As String)
    Select Case myProductType
        Case ProductType.FifthWheels
        Case ProductType.MotorHomes
        Case ProductType.TentCampers
        Case ProductType.TravelTrailers
        Case ProductType.TruckCampers
    End Select
End Sub

Casting to Strings and Concatenation

VB
Dim myString As String = ProductType.FifthWheels
Dim myString As String = "Concatentation" & ProductType.FifthWheels

Looping through Names and Values

You can also loop through the names and values of your enumeration. That simple.

VB
For Each ProductType As String In ProductType.Enum.GetNames
    'Loop through Enumeration Names
Next

For Each ProductType As String In ProductType.Enum.GetValues
    'Loop through Enumeration Values
Next

Identifying a StringEnumeration

VB
If TypeOf(myObject) Is IStringEnumeration Then...

StringEnumeration Class

VB
''' <summary>
''' Base Class for String Enumerations. Fully Represents
''' an Enumeration using Strings. Automatically casts & compares to Strings.
''' </summary>
''' <remarks></remarks>
Public MustInherit Class StringEnumeration(Of TStringEnumeration _
       As StringEnumeration(Of TStringEnumeration))
    Implements IStringEnumeration

    Private myString As String
    Sub New(ByVal StringConstant As String)
        myString = StringConstant
    End Sub

#Region "Properties"
    Public Class [Enum]
        Public Shared Function GetValues() As String()
            Dim myValues As New List(Of String)
            For Each myFieldInfo As System.Reflection.FieldInfo _
                                 In GetSharedFieldsInfo()
                Dim myValue As StringEnumeration(Of TStringEnumeration) = _
                  CType(myFieldInfo.GetValue(Nothing), _
                  StringEnumeration(Of TStringEnumeration))
                  'Shared Fields use a Null object
                myValues.Add(myValue)
            Next
            Return myValues.ToArray
        End Function

        Public Shared Function GetNames() As String()
            Dim myNames As New List(Of String)
            For Each myFieldInfo As System.Reflection.FieldInfo _
                     In GetSharedFieldsInfo()
                myNames.Add(myFieldInfo.Name)
            Next
            Return myNames.ToArray
        End Function

        Public Shared Function GetName(ByVal myName As _
               StringEnumeration(Of TStringEnumeration)) As String
            Return myName
        End Function

        Public Shared Function isDefined(ByVal myName As String) As Boolean
            If GetName(myName) Is Nothing Then Return False
            Return True
        End Function

        Public Shared Function GetUnderlyingType() As Type
            Return GetType(String)
        End Function

        Friend Shared Function GetSharedFieldsInfo() _
                      As System.Reflection.FieldInfo()
            Return GetType(TStringEnumeration).GetFields
        End Function

        Friend Shared Function GetSharedFields() As _
                      StringEnumeration(Of TStringEnumeration)()
            Dim myFields As New List(Of _
                         StringEnumeration(Of TStringEnumeration))
            For Each myFieldInfo As System.Reflection.FieldInfo _
                                 In GetSharedFieldsInfo()
                Dim myField As StringEnumeration(Of TStringEnumeration) = _
                    CType(myFieldInfo.GetValue(Nothing), _
                    StringEnumeration(Of TStringEnumeration))
                    'Shared Fields use a Null object
                myFields.Add(myField)
            Next
            Return myFields.ToArray
        End Function
    End Class
#End Region

#Region "Cast Operators"
    'Downcast to String
    Public Shared Widening Operator CType(ByVal myStringEnumeration _
           As StringEnumeration(Of TStringEnumeration)) As String
        If myStringEnumeration Is Nothing Then Return Nothing
        Return myStringEnumeration.ToString
    End Operator

    'Upcast to StringEnumeration
    Public Shared Widening Operator CType(ByVal myString As String) As _
                           StringEnumeration(Of TStringEnumeration)
        For Each myElement As StringEnumeration(Of TStringEnumeration) In _
                 StringEnumeration(Of TStringEnumeration).Enum.GetSharedFields
            'Found a Matching StringEnumeration - Return it
            If myElement.ToString = myString Then Return myElement
        Next
        'Did not find a Match - return NOTHING
        Return Nothing
    End Operator

    Overrides Function ToString() As String Implements IStringEnumeration.ToString
        Return myString
    End Function
#End Region

#Region "Concatenation Operators"
    Public Shared Operator &(ByVal left As StringEnumeration(Of _
           TStringEnumeration), ByVal right As StringEnumeration(Of _
           TStringEnumeration)) As String
        If left Is Nothing And right Is Nothing Then Return Nothing
        If left Is Nothing Then Return right.ToString
        If right Is Nothing Then Return left.ToString
        Return left.ToString & right.ToString
    End Operator

    Public Shared Operator &(ByVal left As StringEnumeration(Of _
           TStringEnumeration), ByVal right As IStringEnumeration) As String
        If left Is Nothing And right Is Nothing Then Return Nothing
        If left Is Nothing Then Return right.ToString
        If right Is Nothing Then Return left.ToString
        Return left.ToString & right.ToString
    End Operator
#End Region

#Region "Operator Equals"
     Public Shared Operator =(ByVal left As StringEnumeration(Of _
           TStringEnumeration), ByVal right As _
           StringEnumeration(Of TStringEnumeration)) As Boolean
        If left Is Nothing Or right Is Nothing Then Return False
        Return left.ToString.Equals(right.ToString)
    End Operator

    Public Overrides Function Equals(ByVal obj As Object) As Boolean
        If TypeOf (obj) Is StringEnumeration(Of TStringEnumeration) Then
            Return CType(obj, StringEnumeration(Of _
                   TStringEnumeration)).ToString = myString
        ElseIf TypeOf (obj) Is String Then
            Return CType(obj, String) = myString
        End If
        Return False
    End Function
#End Region

#Region "Operator Not Equals"
    Public Shared Operator <>(ByVal left As StringEnumeration(Of _
           TStringEnumeration), ByVal right As StringEnumeration(Of _
           TStringEnumeration)) As Boolean
        Return Not left = right
    End Operator

#End Region

End Class

'Base Interface without any Generics for StringEnumerations
Public Interface IStringEnumeration
    Function ToString() As String
End Interface

I hope this helps you! This has worked great for me.

License

This article, along with any associated source code and files, is licensed under The BSD License


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionnumeric value?? Pin
kooshi27-Sep-12 4:18
kooshi27-Sep-12 4:18 
BugAnother big drawback Pin
PJ-Intellia4-Sep-12 22:34
PJ-Intellia4-Sep-12 22:34 
BugBug detected with string and stringEnumeration concatenation Pin
PJ-Intellia2-Sep-12 9:41
PJ-Intellia2-Sep-12 9:41 
GeneralMy vote of 5 Pin
aaroncampf12-Mar-11 5:58
aaroncampf12-Mar-11 5:58 
GeneralFunctional Use for this Class Pin
aaroncampf12-Mar-11 5:58
aaroncampf12-Mar-11 5:58 
Generalbugs and updates Pin
serhhio14-Aug-09 2:02
serhhio14-Aug-09 2:02 
GeneralRe: bugs and updates Pin
Ryan D. Hatch2-Sep-09 15:53
Ryan D. Hatch2-Sep-09 15:53 
Hi Serhio -

This is a very simple fix, not a bug. Please try this:

  Private NotInheritable Class DbTableName<br />
    Inherits StringEnumeration(Of DbTableName)<br />
    Public Shared ReadOnly Roulement As New DbTableName("PARAM_GRAPHIQUE_ROULEMENT")<br />
    Public Shared ReadOnly Habillage As New DbTableName("PARAM_GRAPHIQUE_HABILLAGE")<br />
    Public Shared ReadOnly Theorique As New DbTableName("PARAM_GRAPHIQUE_THEORIQUE")<br />
    Public Shared ReadOnly Vehicules As New DbTableName("PARAM_GRAPHIQUE_VEHICULES")<br />
<br />
    Private Sub New(ByVal StringConstant As String)<br />
      MyBase.New(StringConstant)<br />
    End Sub<br />
  End Class


Glad you're finding the class useful! Thanks for checking in...

Ryan
GeneralStringEnumeration vs Enum Pin
Zeleks3-Mar-09 2:04
Zeleks3-Mar-09 2:04 
GeneralRe: StringEnumeration vs Enum Pin
Ryan D. Hatch3-Mar-09 21:46
Ryan D. Hatch3-Mar-09 21:46 
GeneralRe: StringEnumeration vs Enum Pin
Zeleks17-Mar-09 2:21
Zeleks17-Mar-09 2:21 
GeneralRe: StringEnumeration vs Enum Pin
Ryan D. Hatch18-Mar-09 16:47
Ryan D. Hatch18-Mar-09 16:47 
GeneralRe: StringEnumeration vs Enum Pin
Zeleks31-Mar-09 2:00
Zeleks31-Mar-09 2:00 
GeneralRe: StringEnumeration vs Enum Pin
Ryan D. Hatch27-Apr-09 5:49
Ryan D. Hatch27-Apr-09 5:49 
GeneralEnumeration Pin
Sike Mullivan26-Feb-09 14:11
Sike Mullivan26-Feb-09 14:11 
GeneralRe: Enumeration [modified] Pin
Ryan D. Hatch26-Feb-09 18:42
Ryan D. Hatch26-Feb-09 18:42 
GeneralMy vote of 1 Pin
Dave Kreskowiak21-Feb-09 7:42
mveDave Kreskowiak21-Feb-09 7:42 
GeneralRe: My vote of 1 Pin
Ryan D. Hatch22-Feb-09 4:24
Ryan D. Hatch22-Feb-09 4:24 
QuestionUmmm... what? Pin
PIEBALDconsult17-Feb-09 8:45
mvePIEBALDconsult17-Feb-09 8:45 
AnswerRe: Ummm... what? [modified] Pin
Ryan D. Hatch18-Feb-09 3:10
Ryan D. Hatch18-Feb-09 3:10 
GeneralRe: Ummm... what? Pin
PIEBALDconsult18-Feb-09 4:08
mvePIEBALDconsult18-Feb-09 4:08 
GeneralRe: Ummm... what? [modified] Pin
Ryan D. Hatch22-Feb-09 17:17
Ryan D. Hatch22-Feb-09 17:17 
GeneralRe: Ummm... what? Pin
PIEBALDconsult23-Feb-09 4:24
mvePIEBALDconsult23-Feb-09 4:24 
GeneralRe: Ummm... what? Pin
Ryan D. Hatch23-Feb-09 4:56
Ryan D. Hatch23-Feb-09 4:56 
GeneralRe: Ummm... what? Pin
PIEBALDconsult23-Feb-09 5:59
mvePIEBALDconsult23-Feb-09 5:59 
GeneralRe: Ummm... what? [modified] Pin
michaeltaylor19-Jul-12 6:40
michaeltaylor19-Jul-12 6:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.