2

So I want to use a string variable to call or declare other stuff. For example: I write down "some_random_name" in a text box and then press a button that calls a function which declares a variable or object called "some_random_name". Another example: I have declared a variable from type integer called "a_variable". I write down this name in a text box and then I press a button that calls a function which shows me the value of "a_variable". The second example can also be done this way:

if (the_wanted_variable == "a_variable") show_value(a_variable);

But that's a different question.

I have found a solution... but I couldn't understand it. It was about Reflections. Maybe a need an easier to understand explanation how to do it (no matter how big it is).

Thanks!

AlexSavAlexandrov
  • 858
  • 2
  • 13
  • 34

4 Answers4

2

Reflection is a way to examine/use the properties/methods of an object at runtime. Some explanations here:

C#: Can someone explain the practicalities of reflection?

Community
  • 1
  • 1
Paddy
  • 33,309
  • 15
  • 79
  • 114
2

Instead of creating different variables for each key/value pair entered by the user, you could store all key/value pairs in one Dictionary.

mbeckish
  • 10,485
  • 5
  • 30
  • 55
2

Reflection is an option; but if the needs of your program are very predictable you can avoid it for a potentially easier solution.

In the example you've given - if the user is presented with a textbox and they enter the name of a variable like 'MyTest1' and can press a button called 'Add 1' you could accomplish it with a key/value pair dictionary.

In other words - if the user enters text that they haven't entered before, you create a new integer value and set it's value to 0. If the user clicks on a button, it calls a predefined function on that value associated with that key. 'Add 1' to a newly created key would return '1'.

Rob P.
  • 14,921
  • 14
  • 73
  • 109
1

You can use a dictionary to store the variables.

Dictionary<string,string> Variables;

if you don't want strings, you can use a Dictionary<string, object> but you have to be aware of the type to cast it when you click the button.

Blau
  • 5,742
  • 1
  • 18
  • 27