Tony
Tony

Reputation: 12705

C# reflection find property which type inherits some other type

I'm wondering how to use the reflection mechanism in the following scenario:

public class A { }
public class B { }

public class ListA : ICollection<A> { }

public class ListB : ICollection<B> { }

public class Container
{
    public ListA LA { get; set; }
    public ListB LB { get; set; }
}

then I want to find a property, which type inherits the type ICollection<B>

var container = new Container();

var found = container.GetType().GetProperties().FirstOrDefault(x => x.PropertyType == typeof(ICollection<B>));

and of course the found variable is null, so how to move deeper with the reflection?

Upvotes: 0

Views: 74

Answers (2)

Samvel Petrosov
Samvel Petrosov

Reputation: 7706

In case if you want to get class which implement some interface, in your case it's ICollection<B>, you can use the following code which use Reflection's GetInterfaces() method:

var container = new Container();

var found = container.GetType().GetProperties().FirstOrDefault(x => x.PropertyType.GetInterfaces().Contains(typeof(ICollection<B>)));

Upvotes: 1

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43916

List<B> is of course not the same type as ICollection<B>. Thatswhy your == fails.

You need to check if the property type can be assigned to an ICollection<B>:

var found = typeof(Container).GetProperties()
              .FirstOrDefault(x => typeof(ITest<B>).IsAssignableFrom(x.PropertyType));

Alternatively you can check the interfaces that the PropertyType implements:

var found = typeof(Container).GetProperties()
              .FirstOrDefault(x => x.PropertyType.GetInterfaces().Contains(typeof(ICollection<B>)));

Upvotes: 5

Related Questions