How to declare a variable using a different variable - vb.net

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

Related

VB.NET Argument Prompt cannot be converted to type string

I'm made a new list of string and when I try to add something there it gives me an error: Argument 'Prompt' cannot be converted to type 'string
My code:
Dim variables As New List(Of String)
Try
variables.Append(CStr(TextBox1.Text))
variables.Append(CStr(TextBox2.Text))
MsgBox(variables)
Catch ex As Exception
MsgBox(ex.Message)
End Try
How can I fix that?
The error is coming from your use of MsgBox(). You're passing it the variables variable, and it doesn't know how to convert a List(Of String) to a String.
As stated by jmcilhinney, you should be using Add() instead of Append().
Additionally, you should use MessageBox.Show() instead of MsgBox().
As for the error, we can only assume you want to see all the current values in your List? If so, one solution is to use String.Join() and display that instead:
Dim variables As New List(Of String)
variables.Add(TextBox1.Text)
variables.Add(TextBox2.Text)
MessageBox.Show(String.Join(",", variables))
But your variables list should be declared at Form level so that you aren't creating a new one each time. It isn't clear from your post if this is the case or not.
You should be calling the Add instance method of your List(Of String). Append is an extension method and is not appropriate in that scenario. Append would be used for an enumerable list that you wanted to enumerate on the spot, e.g.
Dim names = {"Peter", "Paul", "Mary"}
Dim pNames = names.Where(Function(name) name.StartsWith("P"))
For Each pName In pNames.Append("Philip")
Console.WriteLine(pName)
Next
In that case the Append only affects the list being enumerated by the loop where it's used. The original list is unaffected.
You should be using the Add method:
Dim variables As List(Of String) = New List(Of String)
variables.Add(TextBox1.Text)
(No need for the redundant CStr as TextBox1.Text is already of type String.)
As #Mary will no doubt suggest - rightly! - always have Option Explicit and Option Strict set to On (and in my opinion Option Infer Off); it'll help you with any syntax issues.
And always pay attention to the syntax/compiler suggestions in the left margin which will give you clues/tips to fix or improve your code.
Lastly, refer to the Microsoft documentation if in doubt. It should be your first port-of-call if you're unsure of anything.
As several people have mentioned, use the .Add method not .Append.
The .Text property of a TextBox is already a String. No need to convert with CStr().
A message box displays a String. variables is not a String; it is a List(Of String). To see what is in your list use a For Each loop.
Private Sub OpCode()
Dim variables As New List(Of String)
variables.Add(TextBox1.Text)
variables.Add(TextBox2.Text)
For Each s In variables
MsgBox(s)
Next
End Sub
#SteveCinq is correct :-); turn on Option Strict.

VB.Net - when shall I use "New" word?

In declaration of variables and objects, when exactly should I use "New" word, and when shouldn't I use it?
I know that I should declare a string without "New" word:
Dim mystring As String
I also know I should use it declaring a datatable:
Dim mytable As New Datatable()
New creates an object that is an instance of the specified class. If you just write the following then you have a reference, but the reference is Nothing as you didn't actually create a Datatable for it to refer to:
Dim mytable As Datatable
You don't typically use New for value types (Numbers, Dates, Booleans, Structures, Enums - a full list is here), as they always have a value (cannot be Nothing). For example this outputs 0:
Dim num as Int32
Console.WriteLine(num)
I wouldn't worry too much about this, but some value types (structures) can be initialised with New, which is somewhat inconsistent, for example:
Dim dec = New Decimal(2, 3, 4, True, 5)

Dictionary containing an array of strings as value

Is it possible to have a string array as the value in a dictionary? I need to save the description (Hour2) as the key and as value being able to access both the price (elements_PR(4)) and the time offset (1). Is there a good way to do that?
Dim pr_val(2) As String
Dim PR As New Dictionary(Of String, pr_val)
PR.Add("Hour2", {elements_PR(4), "1"})
There is no reason why you can't do it - you could also use values of type Tuple(Of String, String), if the number of elements is fixed in advance - in this case, 2. It'd be easier to perform comparisons on, and would also be immutable, which is often a good idea.
You sure can. Try something like this:
Dim PR As New Dictionary(Of String, IEnumerable(Of String))
PR.Add("Hour2", {elements_PR(4), "1"})
It seems to me that you could create a class representing the price and the time offset. Therefore, you could do something like PR.Add("Hour2", instanceOfClass).
Depending on the meaning of the description in your situation, you could even include it in your class. It would allow you to use another approach with a List(Of YourClass) containing a list of items with the description, the price and the time offset. To retrieve an item by "key", you could then use some Linq.
Short answer - yes. Assuming the following was declared somewhere:
Dim elements_PR(4) As String : elements_PR(4) = "Hello"
Dim PR As New Dictionary(Of String, String())
You can either do:
PR.Add("Hour2", {elements_PR(4), "1"})
or
Dim pr_val() As String = {elements_PR(4), "1"}
PR.Add("Hour1", pr_val)

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

Vb.net combobox name issue

I want to concat two strings and I need the name of a combo box to be the result of concatenation. For example,
parametre = hi
parametre2 = everyone
I have put name hieveryone my combobox name
parametre3 = String.Concat(parametre,parametre2)
dim parametre3 as ComboBox
How can I do solve this problem?
You can't do this. Variable naming occurs at compile time, whereas the string concatenation occurs at execution time.
Generally, if you want to dynamically map strings to values, you should use a Dictionary(Of String, Of ComboBox) or whatever. Then you can put values into the dictionary by string key, and retrieve them later.
Dim parameter1 As New String("Hi");
Dim parameter2 As New String("everyone");
Dim combo As New ComboBox();
combo.Name = String.Concat(parameter1, parameter2);