Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok not to dispose a MemoryStream / StringReader?

Tags:

.net

dispose

I would like to create a method that returns an XmlReader. Depending on the circumstances the XmlReader may be fed different types of streams, either a StringReader or a MemoryStream.

Normally I dispose a StringReader or MemoryStream with a using block, but since I want to return an XmlReader instead, I cannot do that if I want to go with this design. I don't expect the MemoryStream to allocate huge amounts of memory, so I can live with a slight delay in resource deallocation.

Are the consequences of letting the GC dispose StringReader and MemoryStream acceptable in this case?

I should clarify that this is a practical question not a best-practice question. Obviously the theory dictates that I should clean up my own resource allocations, but theory also says that I should prefer the simplest possible design for maximum maintainability. In some cases breaking best-practice can IMHO be justified and my question is whether this concrete case justifies breaking best-practice.

Also this is only about StringReader and MemoryStream, not a general stream or reader. My reason for justifying it in this case is that the actual creation of the StringReader / MemoryStream is well encapsulated in the method that returns the XmlReader, hence it is under control that the XmlReader will not be fed a stream with a limited resource.

like image 492
Holstebroe Avatar asked Dec 09 '22 13:12

Holstebroe


2 Answers

Nothing is going to suffer in this case, but IMO it is still very bad practice. You own them - why not do it properly? Actually, disposing a MemoryStream still can't deallocate etc - it is still bound by GC. But there is a distinct code smell in here somewhere. This can become real problems if anything ever changes, and suddenly it isn't a MemoryStream but something else, etc.

We can't make you dispose it, but personally: I am fastidious about my usings

like image 140
Marc Gravell Avatar answered Jan 08 '23 06:01

Marc Gravell


Answer: NO. You should always dispose disposable resources. In the case of returning a stream from a method, the disposal should be done by the caller.

like image 42
Darin Dimitrov Avatar answered Jan 08 '23 08:01

Darin Dimitrov