So I implemented my own form of Enum static classes so I can associate strings to enumeration values. One of the shared functions in each enum class, GetValue, is used to quickly look up the string value from an internal array via the offset. While all of the enum classes implement the same exact function, the data types of their parameters differ, specific to the enums in each class.
So I come to a point where I want to create a generic class that can use any of the enums by passing it as a generic type parameter. But I cannot find a way to constrain type T in such a way to be able to call each enum’s GetValue function. This is where an interface would come in handy, but VB.NET forbids interfaces for shared methods.
I have a base class that I could constrain to, but the base class doesn’t implement the GetValue method, and I can’t define a generic version of it, because I need to rely on shared properties of each child class in order for GetValue to do its thing.
Is there another way to tackle this?
EDIT:
Here’s what an example enum class looks like. The parent, EBase is nothing special, just hosting common Name, Value, and Type properties, plus two shared operators, op_Equality and op_Inequality. Imagine using a couple of these enum classes with a generic method (or class) and needing to access the GetValue member via the generic type parameter T.
Friend NotInheritable Class EExample
Inherits EBase
Private Sub New()
End Sub
Friend Shared Function GetValue(ByVal Name As String) As Enums
Return Enums(Array.IndexOf(_Names, Name))
End Function
'Num of Enums defined.
Friend Shared ReadOnly MaxEnums As Int32 = 5
'String literals.
Private Shared ReadOnly _Names As String() = New String() _
{"one_adam", "two_boy", "three_charles", "four_david", "five_edward"}
'Enums.
Friend Shared ReadOnly OneA As New Enums(_Names(0), 0)
Friend Shared ReadOnly TwoB As New Enums(_Names(1), 1)
Friend Shared ReadOnly ThreeC As New Enums(_Names(2), 2)
Friend Shared ReadOnly FourD As New Enums(_Names(3), 3)
Friend Shared ReadOnly FiveE As New Enums(_Names(4), 4)
'Enum Values Array.
Friend Shared ReadOnly Values As Enums() = New Enums() _
{OneA, TwoB, ThreeC, FourD, FiveE}
Friend NotInheritable Class Enums
Inherits EBase
Private Sub New()
End Sub
Friend Sub New(ByVal Name As String, ByVal Value As Int32)
MyBase.Name = Name
MyBase.Value = Value
MyBase.Type = GetType(Enums)
End Sub
End Class
End Class
EDIT2:
Here’s how the things are used:
Dim Foo As EExample.Enums
Foo = EExample.TwoB
Debug.Print(Foo.Name)
will print two_boy
How about this as a solution:
EBasethen looks like this:Now your sample code works exactly as before:
And you are dealing with plain instances for you code implementation. The only
Sharedvalues are the fiveEnumsand a private_instancevariable.You can now restrict on
EBase.Does this work for you?
Kumba pointed out that I didn’t expose the
GetValuefunction on theEExampleclass.Just add this to
EExample: