Answered Returning an array from a function

Berrilicious

Member
Joined
Apr 14, 2009
Messages
12
Programming Experience
1-3
I need to return an array but the array size will change from one call of the function to another so I need away to storing the returned array.

The function is as below, and as you can see the returned array will be of different sizes:
VB.NET:
 For Each Wallbracket In WallbracketCollection
                If Wallbracket.s75x75() = True Then
                    If i > 0 Then
                        'Make copy of array before ReDim
                        Array.Copy(SuitableWallbrackets, SuitableWallbracketsHolder, i)
                        'ReDim to allow another value
                        ReDim SuitableWallbrackets(i)
                        'Add original values back
                        Array.Copy(SuitableWallbracketsHolder, SuitableWallbrackets, i)
                        'Add new wallbracket
                        SuitableWallbrackets(i) = Wallbracket.Model
                        'ReDim holder to allow copy of newly added value.
                        ReDim SuitableWallbracketsHolder(i)
                        i = i + 1
                    Else
                        Dim Model As String = Wallbracket.Model
                        SuitableWallbrackets(i) = Model
                        i = i + 1
                    End If
                End If
            Next

Return SuitableWallbrackets

Could anyone shed some light?

Kind regards.
 
Last edited:
Without answering your question directly, would it not be easier to just use List (of T) rather than an array?
 
Ah that might work, Thank you.

Could the ArrayList be returned from function to another class though?

VB.NET:
Dim Wallbrackets As New System.Collections.ArrayList()
Wallbrackets = Wallbrackets.GetWallbrackets()
 
Also worth noting it that when you declare a function, or variable to hold return value, you only specify the type, not how large for example an array need be.
VB.NET:
Dim items() As String = GetItems()
VB.NET:
Function GetItems() As String()
    Dim list As New List(Of String)
    list.Add("item1")
    list.Add("item2")
    Return list.ToArray
End Function
Don't use an ArrayList if you don't need it, use a generic List(Of T) instead, see for example the GetItems function where a String type List is used. The items in this list is strongly typed for the type you specify, the items in ArrayList is Object type and you have to cast them to correct type.
 
Back
Top