03 January 2008

Casting an array

It looks like there is no built in method for converting an array from one type to another. This DOES NOT work...

Dim arInt As Integer() = {1, 2, 3}
Dim arString As String() = arInt

The only solution seems to be to loop through the original array and insert the elements into a new array one at a time. Seems silly to me.

1 comment:

NickV said...

.NET 2+ has Array.ConvertAll. You still have to create a convert function, but it's generic and reusable.

Public Sub DoSomething()
 Dim arInt As Integer() = {1, 2, 3}
 Dim arString As String() = _
  Array.ConvertAll(Of Integer, String)( _
   arInt,
   New Converter(Of Integer, String)( _
    AddressOf IntToString))
End Sub

Public Shared Function IntToString( _
 ByVal i As Integer) As String
 Return i.ToString()
End Function