fork download
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5.  
  6. namespace ConsoleApplication
  7. {
  8. interface IReadOnlyList</*out*/ T> : IEnumerable<T>
  9. {
  10. int Count { get; }
  11. T this[int index] { get; }
  12. }
  13.  
  14. interface IList<T> : IReadOnlyList<T>
  15. {
  16. new int Count { get; }//Note: new
  17. new T this[int index] { get; set; }//Note: new
  18. void Add(T item);
  19. }
  20.  
  21. class List<T> : IList<T>
  22. {
  23. private readonly System.Collections.Generic.IList<T> _innerList;
  24.  
  25. public List(System.Collections.Generic.IList<T> innerList)
  26. {
  27. if (innerList == null) throw new ArgumentNullException("innerList");
  28. _innerList = innerList;
  29. }
  30.  
  31. public int Count
  32. {
  33. get { return _innerList.Count; }
  34. }
  35.  
  36. public T this[int index]
  37. {
  38. get { return _innerList[index]; }
  39. set { _innerList[index] = value; }
  40. }
  41.  
  42. public void Add(T item)
  43. {
  44. _innerList.Add(item);
  45. }
  46.  
  47. public IEnumerator<T> GetEnumerator()
  48. {
  49. return _innerList.GetEnumerator();
  50. }
  51.  
  52. IEnumerator IEnumerable.GetEnumerator()
  53. {
  54. return GetEnumerator();
  55. }
  56. }
  57.  
  58. class Program
  59. {
  60. static void SomeMethod(IReadOnlyList<int> lst)
  61. {
  62. Console.WriteLine("Count from IReadOnlyList: {0}", lst.Count);
  63. Console.WriteLine("First item from IReadOnlyList: {0}", lst[0]);
  64.  
  65. foreach (var i in lst)
  66. Console.WriteLine(i);
  67. }
  68.  
  69. static void SomeMethodUsingReflection(object obj)
  70. {
  71. var iface = obj.GetType().GetInterfaces()
  72. .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof (IList<>));
  73.  
  74. if (iface != null)
  75. {
  76. var countProp = iface.GetProperty("Count");
  77. var count = (int)countProp.GetValue(obj, null);
  78. Console.WriteLine("Count using reflection: {0}", count);
  79. }
  80. }
  81.  
  82. static void MyMethod(IList<int> lst)
  83. {
  84. lst.Add(10);
  85. lst.Add(20);
  86. lst.Add(30);
  87. lst[0] = 40;
  88.  
  89. Console.WriteLine("Count from IList: {0}", lst.Count);
  90. Console.WriteLine("First item from IList: {0}", lst[0]);
  91.  
  92. SomeMethod(lst);
  93. SomeMethodUsingReflection(lst);
  94. }
  95.  
  96. static void Main()
  97. {
  98. var lst = new List<int>(new[] {1, 2, 3}.ToList());
  99. MyMethod(lst);
  100. //Console.ReadKey();
  101. }
  102. }
  103. }
  104.  
Success #stdin #stdout 0.05s 37168KB
stdin
Standard input is empty
stdout
Count from IList: 6
First item from IList: 40
Count from IReadOnlyList: 6
First item from IReadOnlyList: 40
40
2
3
10
20
30
Count using reflection: 6