Wednesday 7 November 2012

Get Specific Property Name Using Expression


Hope the program explains all:

class Program
    {
        static void Main(string[] args)
        {
            SomeClass sc = new SomeClass();
            Console.WriteLine(sc.p1.GetType());

            //RemoteMgr.ExposeProperty(() => SomeClass.SomeProperty);
            MemberInfo member = RemoteMgr.GetMemberInfo((SomeClass p) => p.SomeProperty);
            Console.WriteLine(member.Name);
            Console.ReadKey();
        }
    }

    public class SomeClass
    {
        public string SomeProperty
        {
            get { return "Foo"; }
        }
    }

    public class RemoteMgr
    {
        public static MemberInfo GetMemberInfo<T, U>(Expression<Func<T,U>> expression)
        {
            var member = expression.Body as MemberExpression;
            if (member != null)
                return member.Member;
            throw new ArgumentException("Expression is not a member access", "expression");
        }
    }

No comments:

Post a Comment