fork(1) download
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5.  
  6. class Foo {
  7. public static Type GetEnumerableType(Type type)
  8. {
  9. if (type == null)
  10. throw new ArgumentNullException("type");
  11.  
  12. if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
  13. return type.GetGenericArguments()[0];
  14.  
  15. var iface = (from i in type.GetInterfaces()
  16. where i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>)
  17. select i).FirstOrDefault();
  18.  
  19. if (iface == null)
  20. throw new ArgumentException("Does not represent an enumerable type.", "type");
  21.  
  22. return GetEnumerableType(iface);
  23. }
  24.  
  25. static void Main() {
  26. foreach (var type in new[] {
  27. typeof(IEnumerable<string>),
  28. typeof(List<int>),
  29. typeof(EnumerableTest)
  30. }) {
  31. Console.WriteLine("{0}: {1}",
  32. type.FullName,
  33. GetEnumerableType(type).FullName);
  34. }
  35. }
  36. }
  37.  
  38. class EnumerableTest : IEnumerable<long>, IEnumerable<double> {
  39. IEnumerator<long> IEnumerable<long>.GetEnumerator() {
  40. throw new NotImplementedException();
  41. }
  42. IEnumerator<double> IEnumerable<double>.GetEnumerator() {
  43. throw new NotImplementedException();
  44. }
  45. public IEnumerator GetEnumerator() {
  46. throw new NotImplementedException();
  47. }
  48. }
Success #stdin #stdout 0.02s 38032KB
stdin
Standard input is empty
stdout
System.Collections.Generic.IEnumerable`1[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]: System.String
System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]: System.Int32
EnumerableTest: System.Int64