As many of you that have worked with VB.NET know, and have been irritated by, you can't use a nonconstant variable to size an array.

A simple workaround, reply if this is a problem, is to take input on the size of the array (Yes, I know you can't do this, but wait) Now you create a constant and set it equal to the new input. While this is not the best case scenario for working with many arrays (just go multidimensional).

I hope this helps, and if it is wrong or will cause problems someone tell me but it's worked for me.

Comments
Thanx for enlightening me (thwee)

If you mean redimming it on the fly then yes, I do that too.

Well redimming does not allow you to take input for the size of an array and it serves almost no purpose on top of destroying the contents of the array unless you preserve it. Redimming just like dimming does not let you use a non-constant variable for the new size

Well what I mean is this:
If you have a situation in which you don't know the size an array needs to be, dimming and redimming just wont work, you can't define an array size with a variable.

Example

Dim x as Integer
Dim ExampleInput as Integer
ExampleInput = Val(InputBox("How Many Names do you want to put in?", "Input", 0)
Dim ExampleArray(ExampleInput) as String
For x=0 to (ExampleArray.Length-1)
     ExampleArray(x)  =  InputBox("What is the name?",  "Names",  "John Smith")
Next

It wouldn't even let you build that because you cannot use a non-constant to define the size of an array. But this would work:

Dim x as Integer
Dim ExampleInput as Integer
ExampleInput = Val(InputBox("How Many Names do you want to put in?", "Input", 0)
Const ExampleConst as Integer = ExampleInput
 Dim ExampleArray(ExampleConst) as String
For x=0 to (ExampleArray.Length-1)
     ExampleArray(x)  =  InputBox("What is the name?",  "Names",  "John Smith")
Next

This works and allows you to have a array sized at runtime instead of having a set size.

I don't know what you mean. All of these work fine and only one is a constant.
Dim x As Integer = 12
Dim y As Integer = 10
Dim XY(x, y) As String
Dim XY1(12, 10) As String
Const g As Integer = 12
Dim myArray(g)
Dim c As Integer = Val(InputBox("Enter a number"))
Dim cArray(c) As Integer

@Shawn

If you use an arrayList like in the example link I have provided you can do the same thing with a lot more flexibility

This article has been dead for over six months. Start a new discussion instead.