I want to create objects dynamically by String, but struggle with this piece of code:
using System;
using System.Reflection;
namespace simple.test.project {
public class Dog {
public string Sound { get; set; } = "woof woof";
}
public class Animal<T> where T : new() {
public T GetInstance() {
return new T();
}
}
class MainClass {
public static void Main(string[] args) {
var a = Assembly.GetExecutingAssembly().CreateInstance("simple.test.project.Dog");
Type t_a = a.GetType();
var a_t = typeof(Animal<>);
var g_a_t = a_t.MakeGenericType(t_a);
var o = Activator.CreateInstance(g_a_t);
var dog = o.GetInstance() // object does not contain... message
}
}
}
The last statement var dog= will not be accepted by the compiler because GetInstance would not be known. How the code has to be looks like to get it work?