Why this simple generic code does not compile?

  • Thread starter Thread starter Ympostor
  • Start date Start date
Y

Ympostor

public class TestGenericEnumerator<T> :
System.Collections.Generic.IEnumerable<T>
{
public System.Collections.Generic.IEnumerator<T> GetEnumerator()
{
return null;
}
}


I don't understand why this is returning:

Error 6 'TestGenericEnumerator<T>' does not implement interface member
'System.Collections.Generic.IEnumerable<T>.GetEnumerator()'.
'TestGenericEnumerator<T>.GetEnumerator()' is either static, not public,
or has the wrong return type.

Anyone? :(
 
public System.Collections.Generic.IEnumerator<T> GetEnumerator()

Try this

public System.Collections.Generic.IEnumerator<T> GetEnumerator<T>()
 
Because IEnumerable<T> : IEnumerable, and you haven't implemented the
non-generic form; just add:

System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator() {
return GetEnumerator();
}
 
Try this
public System.Collections.Generic.IEnumerator<T> GetEnumerator<T>()

The T in this method is now a different T to the class's template T
(which the compiler issues a CSO693 warning about) - but this means
that the above doesn't implement the interface, since you could use:

foreach(int i in new
TestGenericEnumerator<string>().GetEnumerator<int>()) {...}

which doesn't do the job of implementing IEnumerable<string>. Good
idea, though.

Marc
 
Marc Gravell escribió:
Because IEnumerable<T> : IEnumerable, and you haven't implemented the
non-generic form; just add:

System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator() {
return GetEnumerator();
}


Thanks! Now it works, but, now I don't understand why I need this cast:

public class TestGenericEnumerator<T> :
System.Collections.Generic.IEnumerable<T>
{
System.Collections.Generic.IEnumerator<T>
System.Collections.Generic.IEnumerable<T>.GetEnumerator()
{
return null;
}

System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator()
{
return (

//why is this cast needed!?
(IEnumerable<T>)
//end cast

this).GetEnumerator();
}
}

Thanks in advance.
 
why is this cast needed!?

Because you switched the generic version to an explicit
implementation, and so there is no this.GetEnumerator()

If you want to do this, consider having a single private
implementation that both the generic and non-generic versions invoke:

private IEnumerator<T> GetEnumerator() {
return null; // the actual implementation
}
IEnumerator<T> IEnumerable<T>.GetEnumerator() {
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
 
Back
Top