-2

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?

Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
Pete
  • 1
  • 1

3 Answers3

1

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

Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
0

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.

Avinash Jain
  • 7,200
  • 2
  • 26
  • 40
0

Here you can see how you can do this. The question is about reflection, but the accepted answer is what you need.

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.

Community
  • 1
  • 1
n_ananiev
  • 189
  • 1
  • 3
  • 12
  • 1
    if you add link to question, maybe it's better to add link to original question rather than duplicate: http://stackoverflow.com/questions/72121/finding-the-variable-name-passed-to-a-function-in-c-sharp – Kamil Budziewski Nov 27 '15 at 09:26
  • 1
    @wudzik while the question is duplicate, I find it more convincing, I will take this advice anyways. Thank you. – n_ananiev Nov 27 '15 at 10:06