3

I have a list of strings that is being read in from a file and filtered, all of which is happening using the yield mechanisms so that it is lazy. I then need to pass this into a method which takes a TextReader.

Is there anything wrong with this method? It seems to work, but wanted to know I had missed something.

public class EnumerableReader : TextReader
{
    private readonly IEnumerator<string> _enumerator;

    public EnumerableReader(IEnumerable<string> lines)
    {
        _enumerator = lines.GetEnumerator();
    }

    public override string ReadLine()
    {
        return _enumerator.MoveNext() ? _enumerator.Current : null;
    }

    protected override void Dispose(bool disposing)
    {
        _enumerator.Dispose();
        base.Dispose(disposing);
    }
}
Schotime
  • 15,707
  • 10
  • 46
  • 75
  • Don't forget to `Dispose` the IEnumerator when you're done. – dtb Jul 02 '13 at 23:09
  • @dtb I'm genuinly curious in this case why Disposing the `_enumerator` actively would be better than letting the garbage collector do it when needed ? Memory consumption? – Simon Belanger Jul 02 '13 at 23:26
  • 2
    @SimonBelanger: Generally, because *though shalt dispose your IDisposables*. In this situation the IEnumerator reads from a file; you'll probably do not want to keep the file open until the GC eventually closes it, but close it deterministically. – dtb Jul 02 '13 at 23:34
  • What if I add the Dispose like how I have updated my example? – Schotime Jul 02 '13 at 23:56

1 Answers1

4

The TextReader Class exposes multiple methods to read data. If you pass an instance to some external code, it may use any of the methods, not just the ReadLine Method.

The methods that you need to override at a minimum are the Read Method and the Peek Method. If you don't override them, they both always returns -1, indicating that the end has been reached. All other methods, including the ReadLine Method, provide default implementations based the Read Method. You can override them (for example, for improved performance), but you are not required to.

From MSDN:

Notes to Inheritors

A derived class must minimally implement the Peek and Read methods to make a useful instance of TextReader.

So your implementation does not work as is.

Community
  • 1
  • 1
dtb
  • 213,145
  • 36
  • 401
  • 431