Advertisement
Guest User

Untitled

a guest
Jul 17th, 2018
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4.  
  5. class myList<T> : IEnumerable<T>
  6. {
  7. T[] list;
  8. int index = -1;
  9.  
  10. public void Add(T obj)
  11. {
  12. if (++index < list.Length)
  13. {
  14. list[index] = obj;
  15. }
  16. }
  17.  
  18. public IEnumerator<T> GetEnumerator()
  19. {
  20. return new TEnum<T>(list);
  21. }
  22.  
  23. IEnumerator IEnumerable.GetEnumerator()
  24. {
  25. return this.GetEnumerator();
  26. }
  27.  
  28. public myList(int size)
  29. {
  30. list = new T[size];
  31. }
  32. }
  33.  
  34. //Implement IEnumerator
  35. class TEnum<T> : IEnumerator<T>
  36. {
  37. T[] _list;
  38. int index = -1;
  39.  
  40. public TEnum(T[] objs)
  41. {
  42. _list = objs;
  43. }
  44.  
  45. //Return if foreach can iterate to next index or not
  46. public bool MoveNext()
  47. {
  48. return (++index < _list.Length);
  49. }
  50. public void Reset()
  51. {
  52. index = -1;
  53. }
  54.  
  55. //Get type-safe value of current array's index
  56. //Its the Implementation of IEnumerator<T>
  57. public T Current
  58. {
  59. get
  60. {
  61. return _list[index];
  62. }
  63. }
  64.  
  65. //It's the implementation of 'IEnumerator'
  66. object IEnumerator.Current
  67. {
  68.  
  69. get
  70. {
  71. //return T Current
  72. return this.Current;
  73. }
  74. }
  75.  
  76. //It's the implementation of IDispose interface
  77. public void Dispose()
  78. {
  79. //Write code to dispose un-needed resource
  80. }
  81. }
  82.  
  83. class Person
  84. {
  85. public string Name { get; set; }
  86. public int Age { get; set; }
  87. }
  88.  
  89. class Program
  90. {
  91. static void Main(string[] args)
  92. {
  93. myList<Person> people = new myList<Person>(3);
  94.  
  95. people.Add(new Person { Name = "Ali", Age = 22 });
  96. people.Add(new Person { Name = "Sundus", Age = 21 });
  97. people.Add(new Person { Name = "Hogi", Age = 12 });
  98. foreach (var item in people)
  99. {
  100. //No need to cast
  101. Console.WriteLine("Name:{0} Age:{1}", item.Name, item.Age);
  102. }
  103. }
  104. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement