String + Variable to retrieve a variable?

Here’s a quick Example of what I would like to do.

string name1 = "John";
string name2 = "Mark";
int personNum = 1;

Debug.Log(this["name"+personNum]); // Prints John
this["name"+2] = "Mike"; // Changes Mark to Mike
Debug.Log(this["name"+2]); // Prints Mike


So as you can see, I’m wondering if it’s possible to form variables using strings/variables/ints for temporary use (setting or getting variables). This works in other languages and obviously 'this[“variable string”] is not the correct C# syntax.

Note: I’m only trying to access pre-defined variables using this method, not create them.


Aha! Found it myself on some C# forums.


this returns the string variable called name1;

You could also create a Hash list and use the variable names as the keys.