1

I'm trying to create a function to parse out all values in a multidimensional Array with all but one dimension given. The details are not relevant, but for this function I need to return an one-dimensional Array containing values of the same type the original multidimensional Array has.

To pass any Array with any dimension to my function, I declared the type of this parameter as Array. However, how would I create a new Array of that specific type (e.g. Integer)?

Currently I have the following code:

Function GetRow(ByVal arr As Array) As Array
    Dim result As (...) 'This should be Integer() if arr contains Integers, etc.
    Return result
End Function

How do I declare the type of result to make it having the same type of values as arr? New Array is not possible as it is declared MustInherit.

1

1 Answer 1

4

Use generics here so the function can handle any type:

Function GetRow(Of T)(ByVal arr() As T) As T()
    Dim result() As T
    ReDim result(arr.Length - 1)
    Array.Copy(arr, result, arr.Length)
    Return result
End Function

Sample usage:

    Dim iarr() As Integer = {1, 2, 3, 4}
    Dim copy = GetRow(iarr)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot. However, this does not seem to be able to accept multidimensional Arrays. I guess this is because you declare the type of arr as arr(), i.e. a one-dimensional Array. Could you possibly explain what I could be doing wrong?
Yes, you'll need another overload for multi-dimensional arrays. Declare the arrays as (,) for 2dim and tweak the code accordingly.
Okay, thanks. It's not fully generic, but I will only work with one, two or three-dimensional arrays anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.