c# – How to get the name of a variable inside a function

Question:

How can you get the name of the variable being passed in the called method?
Only pass as an additional parameter?
Can there be any analogue of CallerMemberNameAttribute just for getting the name of the passed variable?

For example:

var variable = "some_value"; // имя переменной nameof(variable)
DoAction(variable);


public void DoAction(string value)
{
    var valueVariableName = ... // хочу получить имя переменной ("variable")
}

I would be grateful for any thoughts.


Note: It was originally intended to do something like

public void DoAction(string value, [PreviousParameterName] string valueParameterName = null)
{
    var valueParameterName = ... // имя переменной (== "variable")
}

But after clarifying the issue of creating custom attributes (which are processed at compile time), it became clear that it was impossible to do this in a simple way. Naturally, it is inappropriate to use reflection to solve this issue (it might not even work, I did not understand).

Answer:

For example, like this:

static void Main(string[] args)
{
    var world = "Hello, {0}!";
    DoAction(() => world);
}

static void DoAction(Expression<Func<string>> value)
{
    var me = (MemberExpression)value.Body;
    var variableName = me.Member.Name;
    var variableValue = value.Compile()();

    Console.WriteLine(variableValue, variableName);
}

But this will work slowly. And any other similar "technology" will be just as slow. Just because you can persuade the compiler to save the name of a variable only by turning it into a field or property – and there is no way to quickly get the value of a field with an unknown name from an object.

Scroll to Top