Created
June 20, 2014 15:30
-
-
Save AlexArchive/99b2f8f0f5510a6b350d to your computer and use it in GitHub Desktop.
Implementing enumerators manually is painful.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DemonstrationList<T> : IEnumerable<T> | |
{ | |
private const int defaultCapacity = 10; | |
private T[] items = new T[defaultCapacity]; | |
private int count = 0; | |
public void Add(T item) | |
{ | |
if (count == items.Length) | |
{ | |
Array.Resize(ref items, defaultCapacity * 2); | |
} | |
items[count++] = item; | |
} | |
public IEnumerator<T> GetEnumerator() | |
{ | |
return new Enumerator<T>(this); | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
{ | |
return GetEnumerator(); | |
} | |
private class Enumerator<T> : IEnumerator<T> | |
{ | |
private readonly DemonstrationList<T> _parent; | |
private int _index = 0; | |
object IEnumerator.Current | |
{ | |
get { return Current; } | |
} | |
public T Current | |
{ | |
get { return _parent.items[_index++]; } | |
} | |
public Enumerator(DemonstrationList<T> parent) | |
{ | |
_parent = parent; | |
} | |
public bool MoveNext() | |
{ | |
return _index < _parent.count; | |
} | |
public void Reset() | |
{ | |
throw new NotImplementedException(); | |
} | |
public void Dispose() | |
{ | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment