Help with IEnumerable / IEnumerator

  • Thread starter Thread starter rossum
  • Start date Start date
R

rossum

I have been trying to get the IEnumerable interface to compile, and am
having some difficulties.

When I try to compile:

class TestIEnum : IEnumerable<string> {

string[] theStrings;

public IEnumerator<string> GetEnumerator() {
foreach (string s in theStrings) {
yield return s;
}
}
} // end class TestIEnum

I get the error message: "'TestIEnum' does not implement interface
member 'System.Collections.IEnumerable.GetEnumerator()'.
'TestIEnum.GetEnumerator()' is either static, not public, or has the
wrong return type."

I can see that GetEnumerator() is public and not static, so I assume
my error is in the return type. I have tried both string and the
non-generic IEnumerator as return types, neither works.

I noticed that the error message refers to
System.Collections.IEnumerable.GetEnumerator(), the non-generic
version. So I tried fully qualifying the name of GetEnumerator(),
again no joy.

What am I missing here?

Thanks in advance,

rossum
 
Hi,

You are missing the non-generic version. IEnumerable<T> implements
IEnumerable.

Both must be implemented, but commonly the non-generic version is
implemented explicitly and just calls the generic version:

class TestIEnum : IEnumerable<string>
{
public IEnumerator<string> GetEnumerator()
{
...
}

System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
 
rossum said:
I noticed that the error message refers to
System.Collections.IEnumerable.GetEnumerator(), the non-generic
version. So I tried fully qualifying the name of GetEnumerator(),
again no joy.

You have to both implement the generics version (as you did), and also
explicitly implement the old version. e.g.

System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator()
{ return GetEnumerator();
}
 
I have been trying to get the IEnumerable interface to compile, and am
having some difficulties.

When I try to compile:

class TestIEnum : IEnumerable<string> {

string[] theStrings;

public IEnumerator<string> GetEnumerator() {
foreach (string s in theStrings) {
yield return s;
}
}
} // end class TestIEnum

I get the error message: "'TestIEnum' does not implement interface
member 'System.Collections.IEnumerable.GetEnumerator()'.
'TestIEnum.GetEnumerator()' is either static, not public, or has the
wrong return type."

I can see that GetEnumerator() is public and not static, so I assume
my error is in the return type. I have tried both string and the
non-generic IEnumerator as return types, neither works.

I noticed that the error message refers to
System.Collections.IEnumerable.GetEnumerator(), the non-generic
version. So I tried fully qualifying the name of GetEnumerator(),
again no joy.

What am I missing here?

Thanks in advance,

rossum
Thanks Dave and Lucian, that worked fine.

rossum
 
Back
Top