G
Guest
how do I code generic functions to return the next item in an enumeration
a) sorted by name, b) sorted by value c) sorted by declaration
in a round-robin style ?
for example the enum is
Enum Colors
Red = 5
Green = 7
Blue = 16
Yellow = 2
End Enum 'Colors
and the generic functions allow me to code:
Dim next as Colors = GetNextEnumItemByName(colors, colors.green) 'returns
Colors.Red
Dim next as Colors = GetNextEnumItemByValue(colors, colors.green) 'returns
Colors.Blue
Dim next as Colors = GetNextEnumItem(colors, colors.yellow) 'returns
Colors.red
I tried
Private Function GetNextEnumValue(Of T)(ByVal start As T) As T
'get the next (round-robin style) value of an enumeration
Dim enumvalues() As String = [Enum].GetValues(GetType(Colors)) 'get
all enum values
Dim index As Integer = Array.IndexOf(enumvalues, start) 'find the
index of the start value
Dim target As Integer = (index + 1) Mod enumvalues.Length 'this is
the index of the "next" value
Return CType([Enum].Parse(T.GetType, "Red"), T) '*** THIS T.GetType
FAILS ***
End Function
thank you very much. herbert
a) sorted by name, b) sorted by value c) sorted by declaration
in a round-robin style ?
for example the enum is
Enum Colors
Red = 5
Green = 7
Blue = 16
Yellow = 2
End Enum 'Colors
and the generic functions allow me to code:
Dim next as Colors = GetNextEnumItemByName(colors, colors.green) 'returns
Colors.Red
Dim next as Colors = GetNextEnumItemByValue(colors, colors.green) 'returns
Colors.Blue
Dim next as Colors = GetNextEnumItem(colors, colors.yellow) 'returns
Colors.red
I tried
Private Function GetNextEnumValue(Of T)(ByVal start As T) As T
'get the next (round-robin style) value of an enumeration
Dim enumvalues() As String = [Enum].GetValues(GetType(Colors)) 'get
all enum values
Dim index As Integer = Array.IndexOf(enumvalues, start) 'find the
index of the start value
Dim target As Integer = (index + 1) Mod enumvalues.Length 'this is
the index of the "next" value
Return CType([Enum].Parse(T.GetType, "Red"), T) '*** THIS T.GetType
FAILS ***
End Function
thank you very much. herbert