get name of a variable or parameter

c#

Solution

Pre C# 6.0 solution

You can use this to get a name of any provided member:

public static class MemberInfoGetting
{
    public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
    {
        MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
        return expressionBody.Member.Name;
    }
}

To get name of a variable:

string testVariable = "value";
string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => testVariable);

To get name of a parameter:

public class TestClass
{
    public void TestMethod(string param1, string param2)
    {
        string nameOfParam1 = MemberInfoGetting.GetMemberName(() => param1);
    }
}

C# 6.0 and higher solution

You can use the nameof operator for parameters, variables and properties alike:

string testVariable = "value";
string nameOfTestVariable = nameof(testVariable);

Problem

I would like to get the name of a variable or parameter: For example if I have: ``` var myInput = "input"; var nameOfVar = GETNAME(myInput); // ==> nameOfVar should be = myInput void testName([Type?] myInput) { var nameOfParam = GETNAME(myInput); // ==> nameOfParam should be = myInput } ``` How can I do it in C#?

Original source

Related problems