Dynamic build of generics types at runtime

How to create dynamically a type in .Net when it’s only known a string representation of that type, I think it’s an operation known to almost all .Net programmers, but what happened with types with type parameters (or generics) ?

In .Net is possible to create dynamically both generics with a known type, i.e. List<>, and generics with type in turn dynamically built.

Here’s an example:

a) Dynamic generated both type parameter and type

Type collectionType = Type.GetType("System.Collections.Generic.List`1, mscorlib");
if (collectionType == "null")
    throw new InvalidOperationException("Invalid type");
Type genericType = Type.GetType("MyNamespace.MyType, MyAssembly");
Type listWithGeneric = collectionType.MakeGenericType(genericType);
var myList = Activator.CreateInstance(listWithGeneric) as IList;

b) Dynamic generated type parameter with a known type (System.Collection.Generic.List in this case):

Type genericType = Type.GetType("MyNamespace.MyType, MyAssembly");
Type listWithGeneric = typeof(List<>).MakeGenericType(genericType);
var myList = Activator.CreateInstance(listWithGeneric) as IList;
Technorati Tags: ,,

81 thoughts on “Dynamic build of generics types at runtime

  1. Pingback: drugstore online
  2. Pingback: pharmacy canada
  3. Pingback: buy cialis online
  4. Pingback: mazhor4sezon
  5. Pingback: filmfilmfilmes
  6. Pingback: gRh9UPV
  7. Pingback: deiun.flazio.com
  8. Pingback: kertyun.flazio.com
  9. Pingback: canada rx
  10. Pingback: gewrt.usluga.me
  11. Pingback: 9-05-2022
  12. Pingback: kinoteatrzarya.ru
  13. Pingback: TopGun2022
  14. Pingback: Xvideos
  15. Pingback: XVIDEOSCOM Videos
  16. Pingback: hekluy.ucraft.site
  17. Pingback: ivanesva
  18. Pingback: madridbet
  19. Pingback: meritroyalbet
  20. Pingback: meritroyalbet
  21. Pingback: eurocasino
  22. Pingback: canadian drugstore

Comments are closed.