Search code examples
c#portable-class-library

Reflection : get static property name


I need to get the property name of a static property dynamically called as a parameter. Here is my Portable Class Library code:

public partial class Test
    {
        public Test()
        {
            string staticPropName = Test.GetPropName(Test.Row); // result must be "Row" without additional string
            System.Diagnostics.Debug.WriteLine("propName=" + staticPropName);
        }

        public static int Row { get; set; }

        public static string GetPropName(object Property)
        {
            return "Row"; // using reflection
        }
    }

I don't know the name of the property and I don't want to define it with an additional string.


Solution

  • You can't do that - when function is called it gets value of the property and have no idea where this value come from. Your sample is equivalent of

         string staticPropName = Test.GetPropName(42); 
    

    which nobody would expect to return name.

    You can try to require Expression as argument so you can actually inspect what method get called with like following staring point (https://stackoverflow.com/questions/1011109/how-do-you-get-the-name-of-the-property):

    public static string GetPropName<TResult>(Expression<Func<TResult>> expression)
    { 
        MemberExpression body = (MemberExpression)expression.Body;
        return body.Member.Name;
    }
    
    string staticPropName = Test.GetPropName(()=> Test.Prop); 
    

    Note that you need checks to make sure expression is just one you expect and not something like () => Test + 42 or more complex one and report nice error.