Reputation: 5333
is it possible to get the nameof
a variable when its referred to as a list index? The first line in my RUN() method compiles and produces the "x", the second line will not compile, saying the expression does not have a name. But it does have a name - how can I direct it during runtime to get that name, or is this impossible via lists?
class list_experiment
{
public string x = "xx";
public List<string> list;
public list_experiment()
{
list = new List<string>() { x };
}
}
static public void RUN()
{
list_experiment a = new list_experiment();
Console.WriteLine(nameof(a.x));
Console.WriteLine(nameof(a.list[0])); // Doesn't compile
Console.ReadKey();
}
Upvotes: 2
Views: 1956
Reputation: 190986
The value in the list is a reference to the string value **
- there is nothing tying it back to x
which is a reference to the same string.
nameof
is a compile time facility. Adding to a List<T>
is a runtime facility which the compiler can't reasonably track those things for you.
Upvotes: 4