Reputation: 115
I'm having a little problem with creating variable which will be named by list value.
Here is an example with what I want.
for (int i = 0; i < list.Count; i++)
{
//here I want to create variable
//which will be named with list[i]
}
So if list has 2 elements eg.
list[0] = "testName"
list[1] = "andAnotherOne"
I want to create 2 variables, one of them is named testName and the second one andAnotherOne
Can you help me complete it?
Upvotes: 1
Views: 84
Reputation: 6172
You can use dynamic
and ExpandoObject
:
var variables = new List<string> { "variableOne", "variableTwo" };
dynamic scope = new ExpandoObject();
var dictionary = (IDictionary<string, object>)scope;
foreach (var variable in variables)
dictionary.Add(variable, "initial variable value");
Console.WriteLine(scope.variableOne);
Console.WriteLine(scope.variableTwo);
Upvotes: 1
Reputation: 3
In C#, variables are all statically declared. I think you can't do that. Maybe you can try with the reflection but I think it won't able you to do what you want.
Some things I found that could interest you :
Convert string to variable name
Upvotes: 0
Reputation: 222692
Just create A List<string> names = new List<string>()
;
for (int i = 0; i < 5; i++)
{
names.Add("sample" + i);
}
EDIT:
If you want to refer with names then use a dictionary like below,
Dictionary<string, string> myvalues = new Dictionary<string, string>();
Upvotes: 1
Reputation: 993
I believe you need a Dictionary
as said by TaW. This allows you to have the value same as the index.
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("foo","foo"); //index,value of index
if(dictionary.ContainsKey["foo"])
{
string value = dictionary["foo"];
Console.Write(value);
}
I hope I understood your question.
Upvotes: 1