Get name of property as a string

(See below solution I created using the answer I accepted)

I’m trying to improve the maintainability of some code involving reflection. The app has a .NET Remoting interface exposing (among other things) a method called Execute for accessing parts of the app not included in its published remote interface.

Here is how the app designates properties (a static one in this example) which are meant to be accessible via Execute:

RemoteMgr.ExposeProperty("SomeSecret", typeof(SomeClass), "SomeProperty");

So a remote user could call:

string response = remoteObject.Execute("SomeSecret");

and the app would use reflection to find SomeClass.SomeProperty and return its value as a string.

Unfortunately, if someone renames SomeProperty and forgets to change the 3rd parm of ExposeProperty(), it breaks this mechanism.

I need to the equivalent of:

SomeClass.SomeProperty.GetTheNameOfThisPropertyAsAString()

to use as the 3rd parm in ExposeProperty so refactoring tools would take care of renames.

Is there a way to do this?

Okay, here’s what I ended up creating (based upon the answer I selected and the question he referenced):

// <summary>
// Get the name of a static or instance property from a property access lambda.
// </summary>
// <typeparam name="T">Type of the property</typeparam>
// <param name="propertyLambda">lambda expression of the form: '() => Class.Property' or '() => object.Property'</param>
// <returns>The name of the property</returns>
public string GetPropertyName<T>(Expression<Func<T>> propertyLambda)
{
    var me = propertyLambda.Body as MemberExpression;

    if (me == null)
    {
        throw new ArgumentException("You must pass a lambda of the form: '() => Class.Property' or '() => object.Property'");
    }

    return me.Member.Name;
 }

Usage:

// Static Property
string name = GetPropertyName(() => SomeClass.SomeProperty);

// Instance Property
string name = GetPropertyName(() => someObject.SomeProperty);

Now with this cool capability, it’s time to simplify the ExposeProperty method. Polishing doorknobs is dangerous work…

13 Answers
13

Leave a Comment