Click here to Skip to main content
15,946,179 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to change the size of an array based on user input. I have a variable which is an integer that is input by the user. I want to change the size of an array to this integer.
Posted
Updated 16-Jan-16 12:47pm
v2

The length of an array is fixed in VB.NET. If you want to stick to arrays your only option is to allocate a new array of the desired size and copy over existing values from the old one.

You could create a method for this which takes the old array and the new size as parameters and returns the new array which you can then assign to the variable which held the old array up to that point. So it would appear almost as if it was the same array grown.

Another option would be to create a class that encapsulates the array and create an indexer property for it so it can be used like an array to a certain extent.

If you don't actually need an array but just some indexable collection you could use a generic List(of T)[^] instead which would allow you to add elements without reallocating it completely. (Actually this is still what's happening under the hoods in the List-class, you just don't have to deal with it yourself.)
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 16-Jan-16 19:21pm    
Sure, a 5.
It took too long to enter Solution 2, but perhaps a little more detail can be useful. :-)
—SA
Sascha Lefèvre 17-Jan-16 10:07am    
Thank you, Sergey.
It makes no sense. You can set the size of an array only when you initialize it, but if you already use some array, you should already know it:
VB
' For example,
Dim length As Integer = ' ...
Dim myArray As String() = New String(length){}

But when an array is already initialized, you cannot change its size. Don't be confused with the method System.Array.Resize. Despite the function name, it does not change the size of an array, it creates a brand-new one: Array.Resize(T) Method (T[], Int32) (System)[^].

This is a pretty expensive operation; I don't think you really need it. If you want to have some data structure with the same or similar features as with array, but you don't know the final number of elements when you fill it with elements, so you would be able to add more elements anytime, you should use the collection class System.Collections.Generic.List<>:
List(T) Class (System.Collections.Generic)[^].

Note that when you complete adding elements and know that you won't need any more, you can always make an array out of the list instance: List(T).ToArray Method (System.Collections.Generic)[^].

—SA
 
Share this answer
 
Comments
Sascha Lefèvre 17-Jan-16 10:06am    
My 5.
Sergey Alexandrovich Kryukov 17-Jan-16 11:49am    
Thank you, Sascha.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900