Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

If you have a specific type it enumerates, it should implement IEnumerable<T>.

In C# if you want to look at next element without advancing the enumerator.

LinkedList will give more control while you are looping

You can also use Queue but be careful with this collection because every call to dequeue removes item from list. this collection has peek method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top