C#, getting a reference to a property such as CheckBox.Checked


/ Published in: C#
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. // [1] using PropertyOf
  2. PropertyInfo pi1 = PropertyOf(() => Checkbox1.Checked);
  3.  
  4. // [2] Using Lambda to get a PropertyInfo from a CheckBox.Checked property.
  5. // This is a variation of [1]
  6. Expression<Func<bool>> expression = (() => Checkbox1.Checked);
  7. PropertyInfo pi2 = ((expression.Body as MemberExpression).Member as PropertyInfo);
  8.  
  9. // [3] using PropertyHelper
  10. PropertyInfo pi3 = PropertyHelper<CheckBox>.GetProperty(x => x.Checked);
  11.  
  12. // [4] using string name of property.
  13. PropertyInfo pi4 = typeof(CheckBox).GetProperty("Checked");
  14.  
  15. // This proves that all 4 methods are itentical.
  16. Debug.Assert(pi1 == pi2 && pi1 == pi3 && pi1 == pi4);
  17.  
  18. // This is how the PropertyInfo is used to Set (or Get) the value.
  19. pi1.SetValue(Checkbox1, true, null);
  20.  
  21.  
  22. /// <summary>
  23. /// [1]
  24. /// Given a lambda expression of a Property, return the PropertyInfo for the property.
  25. /// http://codebetter.com/blogs/patricksmacchia/archive/2010/06/28/elegant-infoof-operators-in-c-read-info-of.aspx
  26. /// </summary>
  27. /// <typeparam name="T">Property type</typeparam>
  28. /// <param name="expression">Lambda expression</param>
  29. /// <returns>PropertyInfo for property</returns>
  30. internal static PropertyInfo PropertyOf<T>(Expression<Func<T>> expression)
  31. {
  32. MemberExpression body = (MemberExpression)expression.Body;
  33. return (PropertyInfo)body.Member;
  34. }
  35.  
  36. /// <summary>
  37. /// [3]
  38. /// From http://stackoverflow.com/questions/491429/how-to-get-the-propertyinfo-of-a-specific-property
  39. /// </summary>
  40. /// <typeparam name="T"></typeparam>
  41. public static class PropertyHelper<T>
  42. {
  43. public static PropertyInfo GetProperty<TValue>(
  44. Expression<Func<T, TValue>> selector)
  45. {
  46. Expression body = selector;
  47. if (body is LambdaExpression)
  48. {
  49. body = ((LambdaExpression)body).Body;
  50. }
  51. switch (body.NodeType)
  52. {
  53. case ExpressionType.MemberAccess:
  54. return (PropertyInfo)((MemberExpression)body).Member;
  55. default:
  56. throw new InvalidOperationException();
  57. }
  58. }
  59. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.