Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Cannot create an instance because Type.ContainsGenericParameters is true

I'm attempting to deserialize a Generic<T> where T : struct but when I call ctor.Invoke(args); I get the exception "Cannot create an instance because Type.ContainsGenericParameters is true".

How do I pass the generic type I want it to be?

like image 717
bevacqua Avatar asked Mar 17 '11 18:03

bevacqua


3 Answers

Let's say you have a Type t of a generic class which has a parameter-less constructor, and an array of the types to use as the type parameters of the generic class:

Type t = someType;
Type[] genericTypeParameters = someArrayOfTypeParameters;

Call Type.MakeGenericType(), which

Substitutes the elements of an array of types for the type parameters of the current generic type definition and returns a Type object representing the resulting... type

Then construct the object as normal:

    t = t.MakeGenericType(genericTypeParameters);

    object instance = Activator.CreateInstance(t);
like image 167
Stephen Kennedy Avatar answered Oct 27 '22 02:10

Stephen Kennedy


Type.MakeGenericType is probably what you are looking for...

like image 26
Quintin Robinson Avatar answered Oct 27 '22 03:10

Quintin Robinson


You have to create a concrete type first using the MakeGenericType method on your generic type

like image 3
mfeingold Avatar answered Oct 27 '22 03:10

mfeingold