Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use reflection to find the properties which implement a specific interface?

Consider this example:

public interface IAnimal
{
}

public class Cat: IAnimal
{
}

public class DoStuff
{
    private Object catList = new List<Cat>();

    public void Go()
    {
        // I want to do this, but using reflection instead:
        if (catList is IEnumerable<IAnimal>)
            MessageBox.Show("animal list found");

        // now to try and do the above using reflection...
        PropertyInfo[] properties = this.GetType().GetProperties();
        foreach (PropertyInfo property in properties)
        {
            //... what do I do here?
            // if (*something*)
                MessageBox.Show("animal list found");
        }
    }
}

Can you complete the if statement, replacing something with the correct code?

EDIT:

I noticed that I should have used a property instead of a field for this to work, so it should be:

    public Object catList
    {
        get
        {
          return new List<Cat>();
        }
    }
like image 398
Stephen Oberauer Avatar asked Jun 20 '11 17:06

Stephen Oberauer


1 Answers

You can look at the properties' PropertyType, then use IsAssignableFrom, which I assume is what you want:

PropertyInfo[] properties = this.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
    if (typeof(IEnumerable<IAnimal>).IsAssignableFrom(property.PropertyType))
    {
        // Found a property that is an IEnumerable<IAnimal>
    }                           
}

Of course, you need to add a property to your class if you want the above code to work ;-)

like image 156
driis Avatar answered Oct 10 '22 20:10

driis