0

Assuming I've got a class looking like the following one:

public class MyClass<MyType> : MyBaseClass<MyType> where MyType : class, IMyInterface
{
} 

In a first step, I'm getting a List with all types of the classes that implement IMyInterface var typeIMyInterface = typeof(IMyInterface);

var typesThatImplementIMyInterface = AppDomain.CurrentDomain.GetAssemblies()
                                                 .SelectMany(s => s.GetTypes())
                                                 .Where(p => typeIMyInterface .IsAssignableFrom(p) && p.IsClass); 

Then in a second step, I want to loop through these types and create an instance of MyClass for the type in the loop fof further usage.

foreach (Type typeThatImplementsIMyInterface in typesThatImplementIMyInterface)
{
    var myInstance = Activator.CreateInstance<MyClass<typeThatImplementsIMyInterface>>();
}

Unfortunately, the last block of code doesn't work because of a compile-time error "Cannot resolve type typeThatImplementsIMyInterface".

How can I pass this type correctly, so that I can successfully create an instance of the object?

dario
  • 2,861
  • 3
  • 15
  • 34
  • you should use the ungeneric version of [`Activator.CreateInstance`](https://learn.microsoft.com/dotnet/api/system.activator.createinstance?view=net-6.0#system-activator-createinstance(system-type-system-reflection-bindingflags-system-reflection-binder-system-object()-system-globalization-cultureinfo-system-object())). – MakePeaceGreatAgain Feb 09 '22 at 09:48
  • @HimBromBeere unfortunately this doesn't work either. Activator.CreateInstance(typeof(MyClass)); still returns the compile-time error "Cannot resolve type typeThatImplementsIMyInterface". – dario Feb 09 '22 at 09:50

1 Answers1

2

You have to construct the type using Type.MakeGenericType and afterwards call the un-generic version of Activator.CreateInstance:

var d1 = typeof(MyClass<>);
var constructedType = d1.MakeGenericType(new[] { typeThatImplementsIMyInterface });
var instance = activator.CreateInstance(constructedType);
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111