Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an object from RuntimePropertyInfo?

Tags:

c#

reflection

I'm trying to find all properties containing an object that implelents an interface, and execute a method on the object. This is the code I have so far:

foreach (var propertyInfo in this.GetType().GetProperties()
    .Where(xx => xx.GetCustomAttributes(typeof(SearchMeAttribute), false).Any()))
{
    if (propertyInfo.PropertyType.GetInterfaces().Any(xx => xx == typeof(IAmSearchable)))
    {
        // the following doesn't work, though I hoped it would
        return ((IAmSearchable)propertyInfo).SearchMeLikeYouKnowIAmGuilty(term);
    }
}

Unfortunately, I get the error:

Unable to cast object of type 'System.Reflection.RuntimePropertyInfo' to type 'ConfigurationServices.ViewModels.IAmSearchable'.

How can I get the actual object, rather than the RuntimePropertyInfo?

like image 981
DaveDev Avatar asked Jul 23 '12 15:07

DaveDev


1 Answers

You need to get the value from the property with the GetValue method:

object value = propertyInfo.GetValue(this, null);

The this is the "target" of the property, and the null indicates that you're expecting just a parameterless property, not an indexer.

like image 138
Jon Skeet Avatar answered Sep 23 '22 21:09

Jon Skeet