Wednesday, 21 August 2013

custom collection cannot implement IEnumerable

custom collection cannot implement IEnumerable

So I have a generic class Node<T> which looks like this. It just hold the
value and the reference to the next Node<T>
public class Node<T>
{
public T Value { get; set; }
public Node<T> Next { get; set; }
// Some Methods go here
}
There's another class called CustomLinkedList<T> which looks like this
public class CustomLinkedList<T> : IEnumerable<T>
{
Node<T> m_first;
Node<T> m_current;
int m_length;
public CustomLinkedList()
{
m_first = new Node<T>();
m_current = m_first;
m_length = 0;
}
// Adding, removing and other methods go here
}
Baisically CustomLinkedList<T> is the collection of Node<T>s. This is just
a challenge to myself to build a collection like LinkedList<T> (At least
what I think of it to be). The code bellow shows the example of how I
implemented the adding functionality.
public void AddLast(T value)
{
m_current.Value = value;
m_current.Next = new Node<T>();
m_current = m_current.Next;
m_length++;
}
public void AddFirst(T value)
{
Node<T> newFirst = new Node<T>();
newFirst.Value = value;
newFirst.Next = m_first;
m_first = newFirst;
m_length++;
}
There are also AddAfter() and AddBefore() methods alongside with some
RemoveXXX() methods. So I wanted CustomLinkedList<T> to implement
IEnumerable<T> and my GetEnumerator() method looks like this
public IEnumerator<T> GetEnumerator()
{
if (m_length > 0)
{
Node<T> nodeToReturn = m_first;
for (int i = 0; i < m_length; i++)
{
if (nodeToReturn == null)
break;
yield return nodeToReturn.Value;
nodeToReturn = nodeToReturn.Next;
}
}
}
But the compiler complains about following
CustomGenericCollections.CustomLinkedList<T>' does not implement interface
member 'System.Collections.IEnumerable.GetEnumerator()'.
'CustomGenericCollections.CustomLinkedList<T>.GetEnumerator()' cannot
implement 'System.Collections.IEnumerable.GetEnumerator()' because it does
not have the matching return type of 'System.Collections.IEnumerator'.
I can't figure out what is the problem.

No comments:

Post a Comment