Get a C# property name as a string

Recently I came across a situation where I need to pass the name of a property as a string to a constructor. I realized that there is not any in-built framework property or method to achieve so. It makes sense too because the compiler interprets Property Type instead of Property Name. The Property name is for writing human readable (or understandable) code.

If you use this.PropertyName.ToString() then it will convert the value of PropertyName property to string not the name of the property itself.

To achieve this functionality, we can make create a helper function which using Expression Tree to return the name of the property. To understand the solution better (and if you are not familiar with Expression Trees), I recommend to read MSDN: Expression Trees (C#)

Helper function to get property name using expression tree

public static string NameOf<T>(Expression<Func<T>> expr)
{
    return ((MemberExpression)expr.Body).Member.Name;
}

public class MyClass
{
    ---------- Some methods ----------------
    this.MyMethod(NameOf( ( ) => fooObject.Foo))
    // above call will pass the Foo property name i.e. "Foo"
    // as string to MyMethod
}