Reflection - how to compare a list of types

I have a list of instances of different types (these types all come from a supertype). I need to get a sublist that only includes instances of certain types or derivatives. A simplified example would be:

class Program
{
    private class A { }
    private class B : A { }
    private class C : A { }
    private class D : C { }

    static void Main(string[] args) 
    { 
        B b = new B();
        C c = new C();
        D d = new D();

        var typesToHave = new List<Type>();
        typesToHave.Add(typeof(C));

        var result = new List<A>();
        if (typesToHave.Any(t => b.GetType().IsInstanceOfType(t)))
            result.Add(b);
        if (typesToHave.Any(t => c.GetType().IsInstanceOfType(t)))
            result.Add(c);
        if (typesToHave.Any(t => d.GetType().IsInstanceOfType(t)))
            result.Add(d);

    }
}

      

What I'm expecting here is a list with c

and d

, but it doesn't return anything.

Also (but this is secondary) I can't figure out why I can't use the operator is

or as

in the lambda expression like:

if (typesToHave.Any(t => d is t))

      

How can I get the list with c

and d

in the above example?

+3


source to share


3 answers


You have the wrong parameters. IsInstanceOfType requires an instance as the parameter you are passing through Type

.

The following should work.



if (typesToHave.Any(t => t.IsInstanceOfType(d)))

      

+4


source


you can use IsAssignableFrom

if (typesToHave.Any(t => t.IsAssignableFrom(d.GetType()))

      



To use the is

or operator as

, you need to provide a name Type

. Not an instance of the type, how these operators work. For example:

var list = new List<int>();
var ie = list as IEnumerable<int>;

      

+3


source


This is also an alternative that works pretty well:

if (typesToHave.Any(t => b.GetType().IsSubclassOf(t) || b.GetType() == t))
    result.Add(b);
if (typesToHave.Any(t => c.GetType().IsSubclassOf(t) || c.GetType() == t))
    result.Add(c);
if (typesToHave.Any(t => d.GetType().IsSubclassOf(t) || d.GetType() == t))
    result.Add(d);

      

+1


source







All Articles