Correct, the type info that goes inside <>
is a compile time type reference. I.e. the type itself, not the variable that holds Type
instance that describes the type. The reason is because type here is resolved and compile-time, not run-time.
Look at answer https://stackoverflow.com/a/2173115/1556108, specifically section:
Type unboundGenericList = typeof(List<>);
Type listOfInt = unboundGenericList.MakeGenericType(typeof(int));
if (listOfInt == typeof(List<int>))
Console.WriteLine("Constructed a List<int> type.");
Because you're building your type during runtime, you need to use the same approach. Something along the lines of:
var type = Type.GetType("Demo.Namespace.AnimalViewModel, Demo.Assembly", true);
var fooType = Type.GetType("Demo.Namespace.Foo, Demo.Assembly", true);
var closedType = fooType.MakeGenericType(fooType)
var closedInstance = Activator.CreateInstance(closedType);
And you cannot really cast it to compile-time known type, unless you can guarantee that loaded type derives from the compile-time known type. Dynamic typing is exactly that - you handle it dynamically at runtime.