I asked a question about ‘How to read a text file reversely with iterator in C#’ sometime ago. Please see the link
Jon Skeet was very kind to provide a solution for me. But I still have a question how to close the data file when it is read? It seemed that Jon used a delegate to handle the iterator, which was very interesting. But How I can call something like ‘file.Close()’ to release it when the file was processed?
Thanks,
It was just a very regrettable oversight.
The answer is – as normal – to use
try/finallyor ausingstatement. That way the file will be closed even if an exception is thrown, and even if the caller doesn’t iterate all the way back to the start of the file.However, it does rely on the caller calling
Disposeon theIEnumerator<T>. Fortunately that’s handled automatically by aforeachloop in C#, but if you ever useGetEnumerator()/MoveNext()/Currentexplicitly, you should be careful and write code like this:Fortunately there aren’t very many times when you need to do this 🙂
I’ve got more details as to how all of this works under the covers in my iterator implementation article which you may find useful.