I have 5 string variables. Then I put them into a list.
If there a way when looping through the list to the actual name of the string variable?
I have 5 string variables. Then I put them into a list.
If there a way when looping through the list to the actual name of the string variable?
You can create Dictionary<string,string>
and iterate it like this:
var dict = new Dictionary<string, string>();
dict.Add("var1", var1);
... //do it for all variables
foreach (var variable in dict.Keys)
{
var varname = variable;
var varvalue = dict[variable];
}
Key would be variable name, and value would be variable value
No, it is not possible. When adding string variable to List<string>
, only value of the variable stored in the list, not the variable name which is used to store value earlier.
Edit:
you can use expression trees and promote the variable to a closure:
static string GetVariableName<T>(Expression<Func<T>> expr)
{
var body = (MemberExpression)expr.Body;
return body.Member.Name;
}
You can use the method like this:
static void Main()
{
var someVar = 3;
Console.Write(GetVariableName(() => someVar));
}
And finally, you can do it this way with C# 6:
static void Main()
{
var someVar = 3;
Console.Write(nameof(someVar));
}
Still, I don't know what is the reason for doing this. If you need to keep the variable name as a key, do it like @wudzik sugested.