Why this simple generic code does not compile?

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? :(
 
P

Peter Morris

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

Try this

public System.Collections.Generic.IEnumerator<T> GetEnumerator<T>()
 
M

Marc Gravell

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

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

Marc Gravell

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
 
Y

Ympostor

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.
 
M

Marc Gravell

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();
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top