C# › File I/O & Streams

How would you implement a custom Stream subclass to wrap another stream with additional behavior, like counting bytes read?

Advanced

Answer

Inherit from Stream, delegate the core required members (Read, Write, Seek, Length, etc.) to an inner wrapped stream, and inject your custom logic (like incrementing a counter) at the specific override points where you need it — this lets your custom stream be used ANYWHERE a Stream is expected, fully transparently.
public class CountingStream : Stream {
  private readonly Stream _inner;
  public long BytesRead { get; private set; }
  public CountingStream(Stream inner) { _inner = inner; }
  public override int Read(byte[] buffer, int offset, int count) {
    int bytesRead = _inner.Read(buffer, offset, count);
    BytesRead += bytesRead;
    return bytesRead;
  }
  // ... delegate remaining required members (CanRead, Length, Seek, etc.) to _inner
}
Real-world example Tracking upload/download progress transparently by wrapping a network or file stream without modifying the code that consumes it.

Common follow-ups: Which Stream members are ABSOLUTELY required to override versus which have reasonable default implementations already?