aghidini aghidini - 29 days ago 11
C# Question

Who should dispose a Stream? The called method or the caller?

I'm writing an API that exports data to a

Stream
:

public interface IExporter<in T>
{
Task ExportAsync(IEnumerable<T> inputs, Stream output);
}


Probably the various
IExporter
implementations will use a form of
TextWriter
/
StreamWriter
but I don't want to enforce it on the interface.

The main problem with the usage of
StreamWriter
is that by default it closes the underlying stream (I know that there's a constructor but it requires
bufferSize
, I could subclass
StreamWriter
but I don't like it either).

Shall I simply "own" the
Stream
in my
IExporter
implementation (and dispose it by disposing my
StreamWriter
) or are there any better ways to handle this problem?

Answer

The caller should be responsible for the resources. The called method has no information (neither should it have any) whether the provided object will be used by others. So it's a bad decision to dispose any objects provided to a method (e.g. what if this object's lifetime is managed by a Dependency Injection container?)