string + int = variable

Is there a way I can declare a variable from a string and an int? I use C#.


I need something like
string mystring = “Level”;
int myint = 1;
int myintResult = 5;
int mystring+myint (must be → “int Level1”) = myintResult;

I'm not sure what you're after, but every variable need a type. It could be dynamic or static typed. Usually you should use static type variables so you have to decide what type you need / want. If the result should be a string you can just do this:

int myIntVar = 10;
string myNewString = "Some text " +  myIntVar;

this will automatically call myIntVar.ToString() which converts the integer into a string to be able to concat them.

If the result should be an int you have to convert / parse the string into an int. Something like that:

string myStringVar = "5";
int myIntVar = 10;
int myIntResult = int.Parse(myStringVar) + myIntVar;
// myIntResult wil contain 15

Be careful: the string must contain text that can be interpreted as number / integer.

If you think about declaring a variable name at runtime, that's something which isn't really supported by compiled languages. If you want to access a variable via a string identifier you might use a Hashtable / Dictionary.


Here's an example how to use a dictionary to store a value / object / whatever under a unique string name.

If you want to store int values you would declare a generic dictionary like this:

Dictionary<string,int> myDict = new Dictionary<string,int>();

// To add a new "variable" use Add:

// To read or write the stored int just do:
int tmp = myDict["Level1"];

// or to set a new value:
myDict["Level1"] = 20;

A Dictionary always have Key-value pairs. The key is unique for each dictionary, in our case a string. The value is stored along with the key. Dictionaries or HashTables are optimised for fast key-searching and therefore faster then doing it yourself with a List but always slower then using real variables.

Since the key is a string you can create it at runtime:

int currentLevel = 5;
myDict["Level" + currentLevel] = 123;

note: you can only access / use entries that have been added to the dictionary. You can test if a specific key exists with:

if (myDict.ContainsKey("Level25"))

a dictionary would be perfect for this

Dictionary myDic = new Dictionary();

for (int i = 0; i < 10; i++) {
    myDic.Add("Level" + i, 0);

// and later on ...
myDic("Level4") = 392;
// etc!

My C# above may have a few typos in it, but the general idea is there.