Can you iteratively create uniquie variables in VB.NET? - vb.net

In VB.Net I am attempting to create multiple variables iteratively and dynamically based on a list. I have created a List(Of Double) that (depending on another variable) contains x number of Double. Assume that I have already declared Dim varList As List(Of Double), and that I have filled the list with a few values. If, for example, List.Count = 5, I want to:
Dim ListCount As Integer = varList.Count
Do While ListCount > 0
Dim Var(ListCount) As Double = varList(ListCount) ' THIS IS MY PROBLEM
Console.WriteLine("Variable created called Var{0}", ListCount)
ListCount = ListCount - 1
Loop
And so on until Var1. You'll notice I specifically call out the line of code that doesn't work "THIS IS MY PROBLEM" because VB.NET doesn't work that way. If I could get it working, the console output would look something like...
Variable created called Var5
Variable created called Var4
Variable created called Var3
Variable created called Var2
Variable created called Var1
"Dim" seems to be a statement with an annoyingly limited capability. Regardless, you can see a full example of what I am trying to do here: https://dotnetfiddle.net/dJQJOq

Related

How do I insert data from a text file into a 2D Array in VB.Net?

Currently I have these data inside my textfile.txt:
I want to split them up into a 2D array when a comma is met. How do I do so?
This is my code for now. Please do point out the mistakes I made.
Dim priceArray(5, 2) As String
Dim i, j As Integer
Dim data As String
Dim oilpriceFile As System.IO.StreamReader
oilpriceFile = New System.IO.StreamReader("C:\Users\zack\OneDrive\Desktop\oilprice.txt")
For i = 0 To UBound(priceArray)
data = oilpriceFile.ReadLine()
For j = 0 To UBound(priceArray)
priceArray(i, j) = data.Split(",") //there's an error stating "value of type string() cannot be converted into string"
j = j + 1
Next
i = i + 1
Next
There are several things you are doing incorrectly.
First turn on Option Strict in the Project Properties and also under Options on the Tools menu.
You do not declare the increment variables used in For loops.
StreanReader needs to be disposed. You should know this because you always check the documentation before you use an unfamiliar framework class. When you do this you will see a Dispose method. When you see this, it needs to be called when you are through with using it. See Using...End Using.
You don't have to deal with Dispose if you use File.ReadAllLines(). This returns an array of the lines in the file.
A For loop increments the value of the first variable automatically. You do not increment it explicitly or you will skip values.
You have defined a 2 dimensional array. When you call UBound on the array, which dimension are you calling it on?? You must indicate which dimension you are asking about.
UBound(priceArray, 1) and UBound(priceArray, 2)
Where 1 and 2 designate the dimension you are getting.
This is the old vb6 way to get this value. The .net framework provides GetUpperBound() for the same purpose. This method uses the .net zero based rank where GetUpperBound(0) will return upper bound of the first dimension of the array.
The next problem is the use of Spilt. Split returns an array of strings and you are trying to assign it to a single string. It takes a Char as a parameter. You have passed a String. To tell the compiler that you intend a Char follow the String by a lower case c.
A side note. // is the comment indicator in C#. In vb.net use the single quote '.
Private Sub OPCode()
Dim priceArray(5, 2) As String
Dim lines = File.ReadAllLines("C:\Users\zack\OneDrive\Desktop\oilprice.txt")
For i = 0 To priceArray.GetUpperBound(0)
Dim data = lines(i)
Dim splits = data.Split(","c)
For j = 0 To priceArray.GetUpperBound(1)
priceArray(i, j) = splits(j)
Next
Next
End Sub

Cannot access the data from a List(Of List)

I am working on a Revit Add-in and in that add-in I am trying to use a List(Of List(Of Curve)), however I'm having issue accessing the data from the sublists.
Dim ClosedCurveList As New List(Of List(Of Curve))
Dim ClosedCurve As new List (Of Curve)
For i=0 To FinalWallLines.Count-1
If FinalWallLines(i+1).GetEndPoint(0).X = FinalWallLines(i).GetEndPoint(1).X And _
FinalWallLines(i+1).GetEndPoint(0).Y = FinalWallLines(i).GetEndPoint(1).Y And _
FinalWallLines(i+1).GetEndPoint(0).Z = FinalWallLines(i).GetEndPoint(1).Z Then
ClosedCurve.Add(FinalWallLines(i))
Else
TaskDialog.Show("A",ClosedCurve.Count)
ClosedCurveList.Add(ClosedCurve)
TaskDialog.Show("B", ClosedCurveList(ClosedCurveList.Count-1).Count)
ClosedCurve.Clear()
End if
Next
TaskDialog.Show("C", ClosedCurveList.Count)
For i=0 To ClosedCurveList.Count-1
TaskDialog.Show(i,ClosedCurveList(i).Count)
next
So when I run that code, the first TaskDialog.Show("A",ClosedCurve.Count) shows me that all of ClosedCurve are made of 4 curves, which makes sense as all my curves are forming rectangles.
My second TaskDialog.Show("B", ClosedCurveList(ClosedCurveList.Count-1).Count) also return 4 as the count for each of the sublists, as expected.
My third TaskDialog.Show("C", ClosedCurveList.Count) returns 23.
So from that, we can gather than ClosedCurveList is a list of 23 lists of 4 curves.
However, during my loop For i=0 To ClosedCurveList.Count-1, my TaskDialog.Show(i,ClosedCurveList(i).Count) returns 23 0s.
Would anyone know why I am not getting 23 4s as expected when trying to access the count of each of my sublists?
Instead of ClosedCurve.Clear() you should have ClosedCurve = new List(Of Curve).
When you add it to ClosedCurveList you are not adding a copy. You are adding the reference to the object CLosedCurve. And so, when you clear ClosedCurve, it also clears the one which was added in ClosedCurveList because they are references to the same object. By re-assigning a new List(Of Curve) to ClosedCurve, you will now have separate references, like you were originally expecting.

How to declare a variable using a different variable

I want to be able to allow the user to input a string and then use that string to create a different variable. For example:
Dim UserInput As String
UserInput = Console.Readline()
Dim (UserInput) As String
So if the user input "Hello" a new variable called 'Hello' would be made.
Is this possible and if not, are there any alternatives?
The names of variables must be known at compile-time. What you're asking for here is to wait until run-time to know the name. That just doesn't work
What you can do is use a Dictionary(Of String, String) to hold your data.
This code works:
Dim UserInput As String
UserInput = Console.Readline()
Dim UserInputData As New Dictionary(Of String, String)
UserInputData(UserInput) = "Some Value"
Console.WriteLine(UserInputData(UserInput))
So if you enter Bar then the dictionary has this value in it:
The bottom-line is that everything is known at compile-time, but you can store data based on the user input at run-time.
It is currently not possible to dynamically create single variables in VB.net. However, you can use lists or dictionaries (source: Dynamically create variables in VB.NET)
The name of the variable does not matter to the user because they will never see it. They will only ever see the data it holds. There really is no reason for this

Visual basic variable is used before it has assigned value

this code is the same as others it is a random between 1 and 4 yet for some reason it says it is being used before it has a value it is the same code as 3 others that are the same but with different names yet this is happening can someone please help me?
Dim npc As Random
Dim ndamage As Integer
ndamage = npc.Next(1, 4)
If (Playerhealth.Value - ndamage) <= 0 Then
Playerhealth.Value = 0
Else
Playerhealth.Value = Playerhealth.Value - ndamage
End If
In the first three lines of code,
Dim npc As Random
Dim ndamage As Integer
ndamage = npc.Next(1, 4)
you declare npc and use it before it is assigned a value. You should use New to create a new instance:
Dim npc As New Random
Further Explanation
Random is a class, which means that its default value is Nothing (also called null in C#), so before it can be used it needs to be assigned a value. The easiest way in this case is to use New directly in the variable declaration line.
Random is a Class which provides a lot of methods to get different random numbers.
To access these methods you have to create an object (sometimes called instance) of that class.
This is done by the new operator. This operator will allocate new space on the heap (which is a memory area) and will fill it with objects values and references to methods and other objects.
If you skip the new statement, you program tries to access to not allocated memory. In several languages this will end up in an nullpointer exception, in vb.net you get an used before it has assigned value exception.
To solve your problem, create an object of the random class:
Dim npc As New Random

Dynamically create variables in VB.NET

I have been trying to figure this out for some time now and can't seem to figure out an answer to it. I don't see why this would be impossible. I am coding in VB.NET.
Here is my problem:
I need to dynamically create variables and be able to reference them later on in the code.
More Details:
The number of variables comes from some math run against user defined values. In this specific case I would like to just create integers, although I foresee down the road needing to be able to do this with any type of variable. It seems that my biggest problem is being able to name them in a unique way so that I would be able to reference them later on.
Simple Example:
Let's say I have a value of 10, of which I need to make variables for. I would like to run a loop to create these 10 integers. Later on in the code I will be referencing these 10 integers.
It seems simple to me, and yet I can't figure it out. Any help would be greatly appreciated. Thanks in advance.
The best way to do something like this is with the Dictionary(T) class. It is generic, so you can use it to store any type of objects. It allows you to easily store and retrieve code/value pairs. In your case, the "key" would be the variable name and the "value" would be the variable value. So for instance:
Dim variables As New Dictionary(Of String, Integer)()
variables("MyDynamicVariable") = 10 ' Set the value of the "variable"
Dim value As Integer = variables("MyDynamicVariable") ' Retrieve the value of the variable
You want to use a List
Dim Numbers As New List(Of Integer)
For i As Integer = 0 To 9
Numbers.Add(0)
Next
The idea of creating a bunch of named variables on the fly is not something you are likely to see in any VB.Net program. If you have multiple items, you just store them in a list, array, or some other type of collection.
'Dim an Array
Dim xCount as Integer
Dim myVar(xCount) as String
AddButton Event . . .
xCount += 1
myVar(xCount) = "String Value"
'You will have to keep Track of what xCount Value is equal to to use.
'Typically could be an ID in A DataTable, with a string Meaning