Shai
Shai

Reputation: 569

Declaring variable dynamically in VB.net

Is there way I can declare 70 different variables in a loop instead of declaring each one?

I wanted to do something like below:

For i As Integer = 0 To 70
     Dim Para + i  AS OracleParameter
Next

Instead of declaring as below:

Dim Param1 AS OracleParameter
Dim Param2 AS OracleParameter
Dim Param3 AS OracleParameter
…
Dim Param70 AS OracleParameter

Upvotes: 2

Views: 10212

Answers (3)

Jens Lauterbach
Jens Lauterbach

Reputation: 11

Normally this is done by using an array:

Dim Para(70) As OracleParameter

To access an element of the array use Para(0), Para(1) and so on.

If you actually need seperate variables you could write a small programm that prints out the needed code lines and copy&paste these to your code file - but I don't see any reason for doing so :-)

Bye, Jens

Upvotes: 1

Joel Etherton
Joel Etherton

Reputation: 37543

I have never seen such a method, but in looking at it, why wouldn't you use a list or a KeyValuePair using the index as the key? I would really recommend using something of that nature, even if you keep the word "Param" as part of the key.

Dim Parameters as New KeyValuePair(Of String, OracleParameter)

For i AS Integer = 0 To 70
     Parameters.Add("Param" & i.ToString(), New OracleParameter)
Next

This could then be accessed at any time using (e.g.)

Parameters("Param66").Value

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 942438

Use an array:

Dim Param(69) As OracleParameter
For i As Integer = 0 To Param.Length - 1
    Param(i) = New OracleParameter(..)
    '' etc..
Next

Upvotes: 9

Related Questions