Question

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);
    }
}

No correct solution

OTHER TIPS

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.

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