Click here to Skip to main content
15,922,533 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
For my persistence library I would like to create type dynamically.
Unfortunately I have a problem with generic types. The code below fails at runtime and I have no clue why:

var tDict = Type.GetType("System.Collections.Generic.Dictionary`2[]");
var tDict2 = tDict.MakeGenericType(typeof(int), typeof(string));

The exception is:
Additional information: System.Collections.Generic.Dictionary`2[TKey,TValue][] is not a GenericTypeDefinition. MakeGenericType may only be called on a type for which Type.IsGenericTypeDefinition is true.

The following code makes the trick:

private void test()
            Type tDict = Type.GetType("System.Collections.Generic.Dictionary`2[System.Int32, System.String]").GetGenericTypeDefinition();

            var tDict3 = tDict.MakeGenericType(typeof(string), typeof(string));
            var tDict2 = tDict.MakeGenericType(typeof(int), typeof(string));

Share this answer
Super Lloyd 25-Nov-13 10:41am    
Hi, I solved it myself! ;)
Beside I have a type name parser and need to resolve each piece independently, to repair broken Type.GetType(), so I can't use the full type name as above!
Adam Zgagacz 25-Nov-13 12:42pm    
I see. good luck with the rest of your code.
var tDict = Type.GetType("System.Collections.Generic.Dictionary`2");

works!! :)
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900