2

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.)

jor
  • 2,058
  • 2
  • 26
  • 46
  • There's some nice extension methods here: http://stackoverflow.com/questions/105372/how-do-i-enumerate-an-enum?rq=1 – the_lotus Jul 26 '13 at 15:39

1 Answers1

2
<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
jor
  • 2,058
  • 2
  • 26
  • 46
  • I would add a check if the type is an enum `a.IsEnum`. – Styxxy Jul 26 '13 at 10:13
  • @Styxxy: yes thought about this, too. But actually this is implicitely done in `[Enum].GetValues()`, isn't it? – jor Jul 26 '13 at 10:50
  • Yes it is, implicitly. – Styxxy Jul 26 '13 at 10:55
  • I wondered if the **order in the array** would be defined. The answer is yes but surprisingly it is not "as defined." It is (from the [docs](http://msdn.microsoft.com/en-us/library/system.enum.getvalues.aspx)): _The elements of the array are sorted by the binary values of the enumeration constants (that is, by their unsigned magnitude)._ – Tom Blodget Jul 26 '13 at 13:30