Tag Archives: c#

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));


    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");
                return memberExpression.Member.Name;