Create an Enum like variable for String Contants

  • Thread starter Thread starter moondaddy
  • Start date Start date
M

moondaddy

How can I create a public variable similar to an Enum, but rather than
returning integer values it would return String values?
 
Public Class MyStringEnum
Public Const ValueA As String = "First Value"
Public Const ValueB As String = "Second Value"
Public Const ValueC As String = "Third Value"
End Class

Public Class Class1

Public Sub Main()
MsgBox( MyStringEnum.ValueB )
End Sub

End Module


-Rob Teixeira [MVP]
 
Thanks that was perfect.

--
(e-mail address removed)
Rob Teixeira said:
Public Class MyStringEnum
Public Const ValueA As String = "First Value"
Public Const ValueB As String = "Second Value"
Public Const ValueC As String = "Third Value"
End Class

Public Class Class1

Public Sub Main()
MsgBox( MyStringEnum.ValueB )
End Sub

End Module


-Rob Teixeira [MVP]
 
* "moondaddy said:
How can I create a public variable similar to an Enum, but rather than
returning integer values it would return String values?

In .NET, it's not possible to define an enumeration of any type. In some
situation, an enumeration of predefined values/objects is needed. The code
below creates an enumeration of type 'String' called 'ClipboardType'. The
design follows the pattern that is used in the FCL, for example, for
'Color':

\\\
Public Structure ClipboardType
Public Shared ReadOnly Property Rtf() As ClipboardType
Get
Return New ClipboardType("RTF") ' Don't cache them ;-).
End Get
End Property

Public Shared ReadOnly Property Bitmap() As ClipboardType
Get
Return New ClipboardType("Bitmap")
End Get
End Property

Public Shared ReadOnly Property Text() As ClipboardType
Get
Return New ClipboardType("Text")
End Get
End Property

Private Sub New(ByVal Value As String)
m_Value = Value
End Sub

Private m_Value As String

' Alternatively, we could implement a 'ReadOnly' 'Value'
' property or something similar.
Public Overrides Function ToString() As String
Return m_Value
End Function

Public Overloads Overrides Function Equals( _
ByVal obj As Object _
) As Boolean
Return _
DirectCast(obj, ClipboardType).ToString() = m_Value
End Function

' '=' Operator overloading stuff goes here (VB 2005).
End Structure
///

Usage:

\\\
Public Sub Foo(ByVal c As ClipboardType)
MsgBox(c.Equals(ClipboardType.Rtf))
MsgBox(c.Equals(ClipboardType.Bitmap))
MsgBox(ClipboardType.Rtf.ToString()) ' Get the value.
End Sub

Public Sub Test()
Foo(ClipboardType.Bitmap)
End Sub
///
 
Back
Top