nameof is returning the temporary variable inside a loop. any idea how to resolve this scenario. The desired result should be the original name of the variables.
thanks.
https://dotnetfiddle.net/s9ctPF
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string var1 ="asdasd1";
string var2 ="asdasd2";
//this is desired result
Console.WriteLine(nameof(var1));
object[] variableList =
{
var1,var2
};
List<Variable> objectList = new List<Variable>();
foreach (var i in variableList)
{
objectList.Add(new Variable { VariableName = nameof(i), VariableValue = (string)i });
//requirement: dont want i, desired result to be var1 : asdasd1...
Console.WriteLine(nameof(i) " : " i);
}
}
public class Variable
{
public string VariableName { get; set; }
public string VariableValue { get; set; }
}
}
CodePudding user response:
As you've discovered nameof
will literally just give you the name of the variable you are passing it. This isn't too surprising since nameof
is just an expression which is evaluated at compile time.
If the goal is just for a name to travel with the value then you could try a structure that would hold both - be it a class you build or a tuple.
CodePudding user response:
What you are seeing is the expected result, nameof()
is a special syntax only function that will return the name of the variable that you pass in to the function.
so nameof(Myconvoluted.namespace.instance.Q)
will always return "Q"
.
It doesn't evaluate or even look at the target of the expression, it is operating on the expression itself.
If you need a reference to the original name of the variable, then you will need to pass that through to the context in a way that it can be resolved, in this case, why not just instantiate the variableList
up front:
public static void Main()
{
string var1 ="asdasd1";
string var2 ="asdasd2";
//this is desired result
Console.WriteLine(nameof(var1));
List<Variable> variableList =
{
new Variable { VariableName = nameof(var1), VariableValue = var1 },
new Variable { VariableName = nameof(var2), VariableValue = var2 },
};
foreach (var i in variableList)
{
Console.WriteLine(i.VariableName " : " i.VariableValue);
}
}
public class Variable
{
public string VariableName { get; set; }
public string VariableValue { get; set; }
}
if this is too verbose, then put some helpers in there:
public static void Main()
{
string var1 ="asdasd1";
string var2 ="asdasd2";
List<Variable> variableList =
{
new Variable(nameof(var1), var1),
new Variable(nameof(var2), var2),
};
foreach (var i in variableList)
{
Console.WriteLine($"{i.Name}: {i.Value}");
}
}
public class Variable
{
public Variable(string name, object value)
{
Name = name;
Value = value;
}
public string Name { get; set; }
public object Value { get; set; }
}