Istrebitel
Istrebitel

Reputation: 3103

C# Why cannot I write custom IEnumerator for my class

I have a simple class that represents a Vertex in a graph that is most likely a tree. Thus, this class looks like this:

class Vertex {
  public Vertex parent;
  public List<Vertex> children;
}

In unlikely case of loops, I can just link to same vertex as child multiple times.

Now, I made an enumerator that would give every vertex in the graph. So that you can do

foreach (Vertex item in rootVertex)

and get every vertex in the graph. For this, I had to make my class IEnumerable{Vertex} and write GetEnumerator method that yields all Vertexes recursively.

Now, for purposes of drawing the graph, I would like to also have another enumerator in the same class that would return every edge in the graph. So i could do something like

foreach (Point[] item in rootVertex.GetEdges())

And get all edges. For this purpose, to avoid confusion, I removed IEnumerable from my class and implemented two methods like this

public IEnumerator<Vertex> GetVertexes() { ...code... }
public IEnumerator<Point[]> GetEdges() { ...code... }

However, when I try to do

foreach (Point[] item in rootVertex.GetEdges())

It spits error - foreach cannot enumerate over rootVertex because Vertex class does not containin GetEnumerator method.

I tried googling but didnt find wether or not I can or cannot make multiple enumerators on the same class.

Upvotes: 0

Views: 199

Answers (1)

Nenad
Nenad

Reputation: 26717

First and obvious, you should have IEnumerable not IEnumerator as return result:

public IEnumerable<Point[]> GetEdges() { ...code... }

Upvotes: 5

Related Questions