I am porting some Java code to C# and my question is
One of my Java class declarations looks like this:
private class PseudoEnumeration implements Enumeration
Should this be translated to
private class PseudoEnumeration : IEnumerator
or
private class PseudoEnumeration : IEnumerable
and why each case?
Another thing is that the enumerator classes work differently in java and C#. Java has "hasMoreElements" and "nextElement" while C# uses "MoveNext" and "Current".
How would I port a Java function of this form to C#?
public boolean hasMoreElements() {
return (field.hasMoreElements() );
}
EDIT: I know MoveNext returns Bool if field has no more elements. However, it also advances the field to the enumerator to the next element. How do I just check if it has more elements without advancing the enumerator?
Given the current Enumeration
implementation in Java, you should implement the IEnumerator<T>
class, which is the class that enumerates over a collection and provides the methods better fitted to the Java counterpart.
MoveNext
for example returns bool
whether there actually is a next value in the enumeration, and relates to the hasMoreElements
method of Java's Enumeration
.
The IEnumerable<T>
interface does not expose any of the details regarding the current state of the enumeration, like Current
or MoveNext
; it only exposes a GetEnumerator
method that returns an IEnumerator<T>
implementation for the given IEnumerable<T>
.
Hence, it is the IEnumerator<T>
class the one that exposes how to iterate over the collection, the current element, and whether there are more, similar to the Enumeration
interface in Java.