How to use Activator to create an instance of a generic Type and casting it back to that type?

Since the actual type T is available to you only through reflection, you would need to access methods of Store<T> through reflection as well: Type constructedType = classType.MakeGenericType(typeParams); object x = Activator.CreateInstance(constructedType, new object[] { someParameter }); var method = constructedType.GetMethod(“MyMethodTakingT”); var res = method.Invoke(x, new object[] {someObjectThatImplementsStorable}); EDIT You could also define an additional … Read more

.NET: Unable to cast object to interface it implements

I hat the same problems with a library of mine providing “plugin”-functionality… I got it finally working… Here was my problem: I had one main assembly using plugins, one assembly with the plugin (Plugin.dll) AND (important) another assembly providing the plugin-functionality (Library.dll). The Plugin.dll referenced the main assembly (in order to be able to extend … Read more

Fast creation of objects instead of Activator.CreateInstance(type)

I did some benchmarking between these (I would write down the bare minimum details): public static T Instance() //~1800 ms { return new T(); } public static T Instance() //~1800 ms { return new Activator.CreateInstance<T>(); } public static readonly Func<T> Instance = () => new T(); //~1800 ms public static readonly Func<T> Instance = () … Read more

How to dynamically create generic C# object using reflection? [duplicate]

Check out this article and this simple example. Quick translation of same to your classes … var d1 = typeof(Task<>); Type[] typeArgs = { typeof(Item) }; var makeme = d1.MakeGenericType(typeArgs); object o = Activator.CreateInstance(makeme); Per your edit: For that case, you can do this … var d1 = Type.GetType(“GenericTest.TaskA`1”); // GenericTest was my namespace, add … Read more