Jamin
Jamin

Reputation: 1402

Getting nameof what an element references in a foreach

I am trying to get the nameof a variable being passed through a foreach loop.

string[] printThis = {"doesntMatter"};
string[] andThis = {"doesntMatter"};
string[][] arrayOfArrays = {printThis, andThis};

foreach(string element in arrayOfArrays)
{
    string theNameOfTheElement = nameOf(element);
    Console.WriteLine(theNameOfTheElement + " ");
}

Instead of getting the desired result of

printThis andThis

I'm obviously getting just:

element

Is this not allowed? A better way?

Upvotes: 4

Views: 2105

Answers (2)

Mehdi
Mehdi

Reputation: 1731

There is no way to find the name of a variable from by value With nameof you can get string name of Method, Property, Class, variable ... according to nameof docs

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

nameof operator is a lot simpler than you imply: it gives you the name of the variable/field/type/etc. that you pass to it as parameter. In your case that's an equivalent of "element" string.

There is no way to figure out the variable that was used to set a string[][] element, unless you save that information in a separate array or collection:

string[][] arrayOfArrays = {printThis, andThis};
string[] namesOfArrays =  {nameof(printThis), nameof(andThis)};

A better approach is to make a collection of name-array pairs:

var arrayOfArrays = {
    new {Name = nameof(printThis), Array=printThis}
,   new {Name = nameof(andThis), Array=andThis}
};
foreach (var p in arrayOfArrays) {
    Console.WriteLine(p.Name);
    ...
}

Upvotes: 2

Related Questions