08 Dec 2010 @ 1:30 PM 

Here is a static class used to get the name of one of the properties on your class.

public static class MemberName<T>
    {
        public static string Of(Expression<Func<T, object>> expression)
        {
            MemberExpression memberExpression;

            if (expression.Body.NodeType == ExpressionType.Convert)
                memberExpression = expression.Body.To<UnaryExpression>().Operand.To<MemberExpression>();
            else
                memberExpression = expression.Body.To<MemberExpression>();

            return memberExpression.Member.Name;
        }
    }

You can call the class as follows:

string heightPropertyName = MemberName<Person>.Of(x => x.Height);

This allows us to stop using ‘magic’ strings that are not tightly coupled with the actual property. If you change the name of your property, using this class you can always get the new string value of that property. This is most useful when you’re databinding, or passing the name of the property to nhibernate.

This code uses an extension method call To. Which is used to cleanup up your type casting and rearranges the logic to make it easier to follow. The extension method is as follows:

        public static T To<T>(this object obj)
        {
            return (T)obj;
        }

Without the extension method line 8 becomes the following:

memberExpression = (MemberExpression)((UnaryExpression)expression.Body).Operand;
Posted By: boyd21
Last Edit: 14 Apr 2011 @ 09:51 PM

EmailPermalinkComments Off
Tags
Tags: , ,
Categories: .Net, Programming

 Last 50 Posts
Change Theme...
  • Users » 3
  • Posts/Pages » 30
  • Comments » 0
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

GeekPub



    No Child Pages.