fork(2) download
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4.  
  5. public class Test
  6. {
  7. public static void Main()
  8. {
  9. var xClass = new XClass();
  10. xClass.Do();
  11. }
  12. }
  13.  
  14. public class XClass
  15. {
  16. public List<string> list1 = new List<string>();
  17.  
  18. public List<string> list2 { get; set; }
  19.  
  20. public void Do()
  21. {
  22. Console.WriteLine("Type = {0}", GetListType(list1));
  23.  
  24.  
  25. var propertyList = this.GetType().GetProperty("list2"); // i get list from reflection
  26.  
  27. // Create instance of list2
  28. var newList = (IList)Activator.CreateInstance((typeof(List<>).MakeGenericType(propertyList.PropertyType)));
  29.  
  30. Console.WriteLine("Type = {0}", GetListType(newList));
  31. }
  32.  
  33. private Type GetListType(IEnumerable list)
  34. {
  35. return list.GetType().GetGenericArguments()[0];
  36. }
  37. }
Success #stdin #stdout 0.04s 34760KB
stdin
Standard input is empty
stdout
Type = System.String
Type = System.Collections.Generic.List`1[System.String]