LeCintas LeCintas - 23 days ago 4
ASP.NET (C#) Question

Recursively get variable name

I try to get recursively the name of a variable, for example for the variable

test.child
, if I follow this topic, I only get
child
and I have no idea how to get all the parents.

Here is my test code:

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

public class Test
{
public string child = "childValue";
}

static void Main(string[] args)
{
//string testVariable = "value";
Test test = new Test();
test.child = "newValue";
string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => test.child);

Console.WriteLine(nameOfTestVariable + " | " + test.child);
Console.Read();
}

Answer

I throw this in as the first intent: (not 100% done, still thinking about it, at least it handles your sample)

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

        var str = expressionBody.ToString();
        var lst =  str.Split('.').Skip(2).ToList(); //This needs LINQ, otherwise do it manually

        StringBuilder retVal = new StringBuilder();

        for (int i = 0; i < lst.Count; i++) {
            retVal.Append(lst[i]);
            if(i != lst.Count -1) {
                retVal.Append(".");
            }
        }               

        return retVal.ToString();
    }
}