I want to create a var in a for loop, e.g.
for(int i; i<=10;i++)
{
string s+i = "abc";
}
This should create variables s0, s1, s2... to s10.
I want to create a var in a for loop, e.g.
for(int i; i<=10;i++)
{
string s+i = "abc";
}
This should create variables s0, s1, s2... to s10.
Use some sort of
eval
if it is available in the language.Your first example wouldn't work in any language as you are trying to redefine the variable "i". It's an
int
in the loop control, but astring
in the body of the loop.Based on your updated question the easiest solution is to use an array (in C#):
Obviously, this is highly dependent on the language. In most languages, it's flat-out impossible. In Javascript, in a browser, the following works:
Now the variable sq3, for example, is set to 9.
You probably want to use an array. I don't know exactly how they work in c# (I'm a Java man), but something like this should do it:
And read http://msdn.microsoft.com/en-us/library/aa288453(VS.71).aspx
This depends on the language.
Commonly when people want to do this, the correct thing is to use a data structure such as a hash table / dictionary / map that stores key names and associated values.
You may use dictionary. Key - dynamic name of object Value - object
Output: