I want to loop through a list and declare integer variables for every value in List.
Example :
List<string> VariableNames= new List<string>()
{
"length",
"breadth",
"height"
};
OutPut :
int length;
int breadth;
int height;
Is this possible ?
Eric J. has given a good answer but if you still want the list, you can do this:
List<string> variableNames = new List<string>()
{
"length",
"breadth",
"height"
};
Dictionary<string,int> names = variableNames.ToDictionary(name => name, integer => 0);
But here you aren't generating variables, every variableName
(key) is given an integer value which is initialized with a value of 0 and you can access that value with something like :
names["height"] //returns the integer variable associated with that string.
You cannot do this without code generation. However, you may be able to solve your problem by using a dictionary instead.
Dictionary<string, int> names = new Dictionary<string, int>()
{
{ "length", 0 },
{ "breadth", 0 },
{ "height", 0 },
};
You can then do something like
names["length"] = 42;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.