Question

Using reflection can I get the name of the property from inside that property's accessor?

The quest :=

public string FindMyName
{
    get
    {
        string thisPropertyName = ??
    }
}
Was it helpful?

Solution

Simply: don't. You can get the compiler to tell you:

public static string WhoAmI([CallerMemberName] string caller=null)
{
    return caller;
}
...
public string FindMyName
{
    get
    {
        string thisPropertyName = WhoAmI();
        //...
    }
}

This is great for things like OnPropertyChanged:

protected virtual void OnPropertyChanged([CallerMemberName] string caller = null)
{
    var handler = PropertyChanged;
    if(handler != null) handler(this, new PropertyChangedEventArgs(caller));
}
...
public int Foo {
    get { return foo; }
    set { this.foo = value; OnPropertyChanged(); }
}
public string Bar {
    get { return bar; }
    set { this.bar = value; OnPropertyChanged(); }
}

OTHER TIPS

class Program
{
    static void Main()
    {
        var propertyName = Nameof<SampleClass>.Property(e => e.Name);

        MessageBox.Show(propertyName);
    }
}

public class GetPropertyNameOf<T>
{
    public static string Property<TProp>(Expression<Func<T, TProp>> exp)
    {
        var body = exp.Body as MemberExpression;
        if(body == null)
            throw new ArgumentException("'exp' should be a member expression");
        return body.Member.Name;
    }
}

As CallerMemberName was introduced in.NET 4.5 I believe, you can use this workaround:

public static class StackHelper
{
    public static string GetCurrentPropertyName()
    {
        StackTrace st = new StackTrace();
        StackFrame sf = st.GetFrame(1);
        MethodBase currentMethodName = sf.GetMethod();
        return currentMethodName.Name.Replace("get_", "");
    }
}

with usage:

public class SomeClass
{
    public string SomeProperty
    {
        get
        {
            string s = StackHelper.GetCurrentPropertyName();
            return /* ... */;
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top