If I have a variable, I can print its declared name out as follows in C#:
String myVar = "This is a string.";
Console.WriteLine($"This variable is named {(((MemberExpression)((Expression<Func<string>>)(()=>T)).Body).Member.Name)}.");
This prints This variable is named myVar.
However, I would need this inside the scope of its defining function, i.e.
String myVar = f(args);
public String f(args) {
String name = ...
//here goes any code necessary to make name = "myVar"
}
What code do I need to put inside f
to recover the variable name? Is this possible at all? I presume it's a bit more complicated than the previous one.
nameof(myVar)
?f
is confusing, sincemyVar
is the name of the variable being assigned from the result off
, and is not being passed intof
.args
is a reference to data (string value), and it does not know what other references there are outside of the function pointing to the same data.