C# reflection to return all properties in a class whose Type implements a specific interface

Viewed 63

I am trying to use reflection to return all properties in a class whose Type implements the IMyInterface interface.

Here is a simple console app that shows where I am and isolates the issue at hand...

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var parent = new Parent();

            parent.GetPropertiesThatImplementIMyInterface();
        }
    }

    public interface IMyInterface { }

    public class A : IMyInterface { }

    public class B { }

    public class Parent
    {
        public A A { get; set; }
        public B B { get; set; }

        public void GetPropertiesThatImplementIMyInterface()
        {
            var props = this.GetType().GetProperties().Where(p => p.PropertyType.IsAssignableFrom(typeof(IMyInterface)));

            Debug.WriteLine(props.Count());
        }
    }
}

The Debug.WriteLine returns a count of 0 in the GetPropertiesThatImplementIMyInterface method call. It should return a count of 1 for the A property. How can this code be changed to make it do what I need?

2 Answers

The docs of Type.IsAssignableFrom says:

Determines whether an instance of a specified type can be assigned to a variable of the current type.

So an expression like

typeof(A).IsAssignableFrom(typeof(B))

where A and B are reference types, actually checks whether this will compile (without a conversion):

A a = someB;

In your case, you want to check whether the property could be assigned to IMyInterface, so:

IMyInterface x = someProperty;

Therefore, you need:

typeof(IMyInterface).IsAssignableFrom(p.PropertyType)

Not the other way around.

Have you tried reversing the check to fit this?

typeof(IMyInterface).IsAssignableFrom(p.PropertyType)
Related