What’s your name?

20 Apr

In .NET, having access to the name of a property can be valuable in several scenarios, such as data-binding. However, hard-coding the name of the property in the designer or in a string variable is error prone and can be a pain to deal with when refactoring. We need an easy way to get the “code” name of an object’s property, not it’s property value.

The Props class below has a static method for getting the name (as a string) of a given object’s property. This method uses the generic Expression type to build an expression tree and access the member (property/field) information. I wish there was a way to get rid of the “() =>” syntax, but I can’t seem to find one.

Try it out:

using System;
using System.Linq.Expressions;

namespace PropertyNames
{
    class Program
    {
        static void Main(string[] args)
        {
            Car audi = new Car();

            Console.WriteLine("The name of the property with the engine data is {0}",
                Props.GetName(() => audi.Engine));

            Console.WriteLine("The name of the property with the spoiler flag is {0}",
                Props.GetName(() => audi.HasSpoiler));

            Console.Read();
        }
    }

    internal class Car
    {
        public bool HasSpoiler { get; set; }
        public string Engine { get { return "V8";} }
    }

    internal static class Props
    {
        public static string GetName<T>(Expression<Func<T>> expression)
        {
            MemberExpression memberExpression = expression.Body as MemberExpression;
            if (memberExpression == null)
                throw new ArgumentException("Property specified is invalid");
            else
                return memberExpression.Member.Name;
         }
    }
}

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: