With Java Iterator
s, I have used the hasNext
method to determine whether an iteration has more elements (without consuming an element) -- thus, hasNext
is like a "Peek
" method.
My question: is there anything like a "hasNext
" or "Peek
" method with C#'s generic IEnumerator
s?
No, unfortunately there isn't.
The
IEnumerator<T>
interface only exposes the following members:Methods:
Properties:
Nope, just
MoveNext
,Reset
andCurrent
.No, but in C# you can repeatedly ask for the current element without moving to the next one. It's just a different way of looking at it.
It wouldn't be too hard to write a C# class to take a .NET-style
IEnumerator
and return a Java-styleIterator
. Personally I find the .NET style easier to use in most cases, but there we go :)EDIT: Okay, this is completely untested, but I think it will work. It does at least compile :)
Enumerators are often lazily evaluated so HasNext makes little sense.
You can also try having a look at this Implementing Peek to IEnumerator and IEnumerator<>. It's an extension method that adds the Peek functionality to IEnumerator. Hope it helps. :)