Search code examples
c#reflectionproperties

Is it possible to obtain the name of a variable from the method in which it is a ref argument?


I have two methods, where one of the parameters is referenced from the first to the second.

public double myFirstDouble = 1;
public double mySecondDouble = 2;


public double Calculate()
{
    // do stuff

    GetString(ref myFirstDouble);
    GetString(ref mySecondDouble);

    // ret something;
}

I want the parameter's name in the call site to be returned. In the method below, for example, myFirstDouble, or mySecondDouble, should be returned instead of myParameter.

public string GetString(ref double myParameter)
{
    return nameof(myParameter);
    // return myParameter.ToString();
}

Solution

  • If you are running later C# versions (I think C#10+), you can make use of CallerArgumentExpression attribute to annotate the parameter.

    using System.Runtime.CompilerServices;
    
    public string GetString(ref double myparameter,
    [CallerArgumentExpression(nameof(myparameter))] string myparameterExpression = "") 
    {
        return myparameterExpression + myparameter.ToString();
    }