jor
jor

Reputation: 2157

Convert Enumeration to an Integer Array With an Extension Method

Assumed there is an enumeration:

Public Enum MyEnum
    Value1 = 100
    Value2 = 200
    Value3 = 300
End Enum

How can an extension method be implemented to get an integer array of all values of this enumeration?

Dim ints As Integer() = GetType(MyEnum).ToIntArray()
' result: ints = {100, 200, 300}

(I've already seen that the extension method must base on a type.)

Upvotes: 2

Views: 1388

Answers (1)

jor
jor

Reputation: 2157

<System.Runtime.CompilerServices.Extension()> _
Public Function ToIntArray(Of T As Type)(a As T) As Integer()
    Return [Enum].GetValues(a).Cast(Of Integer)().ToArray
End Function

Upvotes: 2

Related Questions