Alexander Oh
Alexander Oh

Reputation: 25661

Getting All Generic Types in C# from an Assembly

I need to get a list of generic types of a library to filter them for certain traits. I'm trying to test if an interface implementation implements the interface contract correctly, and try to list all types that inherit from that interface, but the interface contains a generic parameter.

The issue that I think this approach has is that if a test/assembly does not generate an instance of the generic type, it will not contain a reference to that type.

I have already found:

    public class MyClass<T>
    {
        public T t { get; set; }

        public MyClass(T t)
        {
            this.t = t;
        }
    }

    public class SimpleTest
    {

        [Fact]
        public void TestCreateMyClass()
        {
            var types = AppDomain.CurrentDomain.GetAssemblies()
                                 .SelectMany(s => s.GetTypes())
                                 .Where(p => p.GetType().FullName.Contains("MyClass")).ToArray();
            Assert.NotEmpty(types); // fails
        }
    }

My current workaround for this is to explicitly list all classes of that type to make a check, but I would prefer some automated way as people are expected to extend this functionality and I want them to be automatically tested.

Upvotes: 0

Views: 1071

Answers (1)

Guru Stron
Guru Stron

Reputation: 143513

You can check if your type has an interface which is generic (IsGenericType) and which GetGenericTypeDefinition() is equal to your generic type interface:

interface IGeneric<T> { }

public class MyClass<T> : IGeneric<T> { }

public class MyClassConcrete : IGeneric<int> { }

var assembly = typeof(IGeneric<>).Assembly; // get assembly somehow

var types = assembly.GetTypes()
    .Where(t => !t.IsInterface)
    .Where(t => t.GetInterfaces().Any(i => i.IsGenericType && typeof(IGeneric<>) == i.GetGenericTypeDefinition()));

Console.WriteLine(string.Join(", ", types)); // prints MyClass`1[T], MyClassConcrete

Upvotes: 1

Related Questions