/ Published in: C#
It\'s not possible to get a reference to a property in C#. A reference would allow getting/setting a property inside another function or while enumerating a list. The infoof operator would work but it doesn\'t exist yet. This code shows several ways to get a PropertyInfo for a given property. #4 is the simplest but has the disadvantage that the string will not auto-rename.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
// [1] using PropertyOf // [2] Using Lambda to get a PropertyInfo from a CheckBox.Checked property. // This is a variation of [1] PropertyInfo pi2 = ((expression.Body as MemberExpression).Member as PropertyInfo); // [3] using PropertyHelper // [4] using string name of property. // This proves that all 4 methods are itentical. Debug.Assert(pi1 == pi2 && pi1 == pi3 && pi1 == pi4); // This is how the PropertyInfo is used to Set (or Get) the value. pi1.SetValue(Checkbox1, true, null); /// <summary> /// [1] /// Given a lambda expression of a Property, return the PropertyInfo for the property. /// http://codebetter.com/blogs/patricksmacchia/archive/2010/06/28/elegant-infoof-operators-in-c-read-info-of.aspx /// </summary> /// <typeparam name="T">Property type</typeparam> /// <param name="expression">Lambda expression</param> /// <returns>PropertyInfo for property</returns> internal static PropertyInfo PropertyOf<T>(Expression<Func<T>> expression) { MemberExpression body = (MemberExpression)expression.Body; return (PropertyInfo)body.Member; } /// <summary> /// [3] /// From http://stackoverflow.com/questions/491429/how-to-get-the-propertyinfo-of-a-specific-property /// </summary> /// <typeparam name="T"></typeparam> public static class PropertyHelper<T> { public static PropertyInfo GetProperty<TValue>( Expression<Func<T, TValue>> selector) { Expression body = selector; { body = ((LambdaExpression)body).Body; } switch (body.NodeType) { case ExpressionType.MemberAccess: return (PropertyInfo)((MemberExpression)body).Member; default: } } }