Question

I saw a couple of examples on how to make an expression which would extract the name of the variable used in the expression. That's great, but I need to extract the name of the variable which was passed as a function parameter and I need that inside the function.

From the below example I need to make something which would enable the Guess function to return "guessMyName" name.

Is this possible?

class NameSample
{
    static internal void Test()
    {
        string message1 = "";
        string message2 = "";

        string guessMyName = "my value";

        // guessMyName: my value
        message1 = GetName(() => guessMyName) + ": " + guessMyName;

        // parameter: my value
        message2 = Guess(guessMyName);
    }

    static internal string Guess(object parameter)
    {
        return GetName(() => parameter) + ": " + parameter;
    }

    static internal string GetName<T>(Expression<Func<T>> expr)
    {
        return (expr.Body as MemberExpression).Member.Name;
    }
}
Was it helpful?

Solution

No, it's not possible. Variable names only exist in the scope of the method that declare them.

What is passed to the method is not the variable itself, but the value of the variable, so you can't access the name. And even in the case of ref parameters, what is passed is the memory location of the variable, without its name.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top