How to create instance of generic class using reflection

In this post, I am going to show how to create an instance of a generic class using c# reflection. The trick is to use the MakeGenericType to make the argument(s) and then call create Instance. Here is a code snippet:

Type d1 = typeof(List<>);
Type[] typeArgs = { typeof(string) };
Type makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);
List<string> itsMe = o as List<string>;

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post