1

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"
2
  • 1
    What do you expect to get inside tester if someone calls it with e.g. tester("foo") or tester(a + b)? Commented Dec 7, 2009 at 21:15
  • possible duplicate of Get property name and type using lambda expression Commented Apr 30, 2013 at 5:40

3 Answers 3

9

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);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I'm getting The non-generic type 'System.Windows.Expression' cannot be used with type arguments
for "public static void Tester<TValue>(Expression<Func<TValue>> selector) "
0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.