13

I need to craft a Stream that will only support Read() operation - the stream will be readonly and non-seekable. Still I have to implement a lot of properties such as Position (which will throw a NotImplementedException) - that's a lot of boilerplate code.

Is there perhaps some standard implementation for such stream where I only need to override the Read() operation?

9
  • Inherited from any Stream and override CanWrite and CanSeek to return false.
    – leppie
    Apr 3, 2014 at 9:40
  • Are you delegating to another stream, or do you already have all the data? MemoryStream allows you to create a read-only version (although it is seekable).
    – Jon Skeet
    Apr 3, 2014 at 9:41
  • @JonSkeet: Good thing it is not sealed, so you can override CanSeek there :)
    – leppie
    Apr 3, 2014 at 9:42
  • 1
    @JonSkeet: I have all the data but inheriting from MemoryStream would mean that my class is a flavor of MemoryStream which it is really not.
    – sharptooth
    Apr 3, 2014 at 9:50
  • 2
    You can chain Stream objects together easily, the Read() method simply calls the previous stream's Read() method. Compare to BufferedStream, without the buffer. Encapsulation, not inheritance, pass the previous stream reference through the constructor. You don't care what flavor stream that is, just that it is readable. Apr 3, 2014 at 10:04

2 Answers 2

18

You can use the constructor new MemorySream(byte[] buffer, bool writeable) (documentation).

Setting the writeable parameter to false will make the stream readonly.

12

Such a stream does not exist in the BCL. You have to write it. In my life I have implemented about a dozen such streams and it is not too bad. The 2nd one is much easier because you can use the first one as a template.

I recommend that you inherit from Stream and not from some other stream. If you were inheriting from MemoryStream you'd abuse inheritance to save code which is not its primary purpose. Your derived stream would not work like a MemoryStream and it is-not a MemoryStream.

Prefer composition over inheritance.

1
  • 7
    +1 "If you were inheriting from MemoryStream you'd abuse inheritance to save code which is not its primary purpose.". That's what I was tempted to do. Jan 21, 2016 at 18:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.