How to get an object from RuntimePropertyInfo?

c#, reflection

Solution

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.

Problem

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`?

Original source