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.

iamthwee commented: Thanx for enlightening me (thwee) +8

Recommended Answers

All 8 Replies

Member Avatar for iamthwee

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

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

Member Avatar for iamthwee

Well obviously you would preserve it. I don't get what you mean.

Explain with a piece of code.

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

Member Avatar for iamthwee

@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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.