Home > Mobile >  Get variable name from object array
Get variable name from object array

Time:02-10

Can't find out how to get element variable name from array.

Need something like that:

var test = 1;
var test2 = "2";

var array = new object[]{test, test2};
foreach (var v in array)
{
 Debug.Log($"{v.ToString()} {v}")
}

// test 1
// test2 2

I need that in one method, lets call it "void CombineWithName(params object[] msg){}

CodePudding user response:

This is impossible. The names test1 and test2 are not stored in the variable array but pointers to the location of the data. Using .net6 on .NETFiddle and the nameof method, the compiler tells you that the expression does not have a name.

.NETFiddle

CodePudding user response:

The nameof operator allows you to get the name of a variable, type or member in string form without hard-coding it as a literal.

 var myVar = "ABC";
 Console.WriteLine(nameof(myVar));

Source: https://riptutorial.com/csharp/example/363/basic-usage--printing-a-variable-name

Edited:

In your above approach, since you are directly mapping variables to an object, There is no way to figure out the variable that was used to set a element, unless you save that information in a separate array or collection (For debug purpose)

var test = 1;
var test2 = "2";

var array = new object[]{test, test2};

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

CodePudding user response:

Maybe you need something like that?

Console.WriteLine(nameof(System.Collections.Generic));  // output: Generic
Console.WriteLine(nameof(List<int>));  // output: List
Console.WriteLine(nameof(List<int>.Count));  // output: Count
Console.WriteLine(nameof(List<int>.Add));  // output: Add
  • Related