views:

92

answers:

3

How could I make this work?:

public class myClass
{
 public string first;
 public int second;
 public string third;
}

public string tester(object param)
{
 //Catch the name of what was passed not the value and return it
}

//So:
myClass mC = new myClass();

mC.first = "ok";
mC.second = 12;
mC.third = "ko";

//then would return its type from definition :
tester(mC.first) // would return : "mc.first" or "myClass.first" or "first"
//and 
tester(mC.second) // would return : "mc.second" or "myClass.second" or "second"
+8  A: 

In the absence of infoof, the best you can do is Tester(() => mC.first) via expression trees...

using System;
using System.Linq.Expressions;
public static class Test
{
    static void Main()
    {
        //So:
        myClass mC = new myClass();

        mC.first = "ok";
        mC.second = 12;
        mC.third = "ko";
        //then would return its type from definition :
        Tester(() => mC.first); // writes "mC.first = ok"
        //and 
        Tester(() => mC.second); // writes "mC.second = 12"
    }
    static string GetName(Expression expr)
    {
        if (expr.NodeType == ExpressionType.MemberAccess)
        {
            var me = (MemberExpression)expr;
            string name = me.Member.Name, subExpr = GetName(me.Expression);
            return string.IsNullOrEmpty(subExpr)
                ? name : (subExpr + "." + name);
        }
        return "";
    }
    public static void Tester<TValue>(
        Expression<Func<TValue>> selector)
    {
        TValue value = selector.Compile()();

        string name = GetName(selector.Body);

        Console.WriteLine(name + " = " + value);
    }
}
Marc Gravell
We are not worthy...
grenade
Well done, Sir.
ongle
I'm getting The non-generic type 'System.Windows.Expression' cannot be used with type arguments
Enriquev
for "public static void Tester<TValue>(Expression<Func<TValue>> selector) "
Enriquev
Probably missing a using statement; I'll in the required ones...
Marc Gravell
This also only works in .NET 3.5, mind...
Marc Gravell
A: 

This is not possible. Variable names don't exist in compiled code, so there's no way you can retrieve a variable name at runtime

Thomas Levesque
A: 

That's not possible. "param" will have no information on where the value came from.

When calling tester(), a copy of the value in one of the properties is made, so the "link" to the property is lost.

Philippe Leybaert