user1 user1 - 2 months ago 6
C# Question

Is it possible to test whether an interface inheits another interface using reflection?

So I have the following

Interface
:

public interface Interface2 : Interface1
{
//Properties here
}


and a
Class
like so:

public class MyClass
{
public Interface2 MyDataAccess { get; set; }

public void TestInheritance()
{
foreach (var property in typeof(MyClass).GetProperties())
{
var type = property.PropertyType;
var inheritsproperty = type.IsAssignableFrom(typeof(Interface1));
if (type is Interface1 || inheritsproperty)
{
//never hit
}
}
}
}


and looking at it I would expect the above code to work,

But the
inheritsProperty
property is always false, and
type is Interface1
is always false.

So is it possible to check if one interface inherits another using reflection? What am I doing wrong?

Answer

You should swap the types: (tested)

var inheritsproperty = type.IsAssignableFrom(typeof(Interface1));

Should be:

var inheritsproperty = typeof(Interface1).IsAssignableFrom(type);

It's kinda vague naming, but it says, Can you assign <parameter> to the caller/source type.


Makes:

public class MyClass
{
   public Interface2 MyDataAccess { get; set; }

   public void TestInheritance()
   {
        foreach (var property in typeof(MyClass).GetProperties())
        {
            var type = property.PropertyType;

            var inheritsproperty = typeof(Interface1).IsAssignableFrom(type);

            if (inheritsproperty)
            {
                //does hit
            }
        }
   }
}