Enumerable stream

As MVP Dustin R. Campbell points out on his blog the Stream.ReadByte() has a pretty bad code smell:

First of all, it returns an int instead of a byte. Initially, that should seem strange since the method specifically states that it's a byte generator. ReadByte returns -1 when the current position is at the end of the stream. Because -1 is not expressible as an unsigned byte, ReadByte returns an int. Of course, that's the second problem: extra non-obvious information is encoded into the result value of this function. However, unless you read the documentation, there's no way of knowing that.

He then suggests a solutions for F#. Here's an elegant C# 3.5 equivalent:

class Program 
{ 
    static void Main(string[] args) { 
        FileStream fs = new FileStream(@"C:Windowssystem.ini", FileMode.Open); 
        foreach (byte b in fs.AsEnumerable()) 
            Console.Write(b.ToString("x")); 
        fs.Dispose(); 
    } 
}  

static class StreamEnumerabler {
public static IEnumerable<byte> AsEnumerable(this Stream _stream) { for (int b; (b = _stream.ReadByte()) > -1; ) yield return unchecked((byte)b); } }

Google
m@kli.dk @klinkby RSS feed  GitHub