Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to get the PropertyInfo from the getter of that property?

Is there any way I can get the PropertyInfo for a property from its getter? Like this:

public object Foo
{
    get
    {
        PropertyInfo propertyInfoForFoo = xxx;
        ...
    }
}

I want to avoid having to hard code the name of the property as a string, as that's tricky to maintain.

I'm using .NET 2.0, so I'm hoping for a linq-less solution.

like image 337
Jon B Avatar asked Aug 14 '10 13:08

Jon B


1 Answers

MethodBase.GetCurrentMethod() will return the MethodInfo object for get_YourPropertyName.

PropertyInfo property = GetType()
                            .GetProperty(MethodBase
                                             .GetCurrentMethod()
                                             .Name
                                             .Substring("get_".Length)
                                        );
like image 50
Kirk Woll Avatar answered Sep 28 '22 23:09

Kirk Woll