0

I have a MemoryStream inside a method. MemoryStream is RAM.

  1. What happens to the Memory if I don't dispose it and method finishes execution? It gets disposed because it is inside the '{}' of method??

  2. I pass that MemoryStream as argument to another method, do I need to dispose it there?

jps
  • 20,041
  • 15
  • 75
  • 79
  • 1
    `MemoryStream` has a `Dispose` method because it inherits from `Stream` and *most* streams have unmanaged resources they should clean up. `MemoryStream` is an exception since it only allocates memory, a managed resource – Damien_The_Unbeliever Mar 08 '23 at 12:09
  • 1
    See https://stackoverflow.com/questions/4195746/memorystream-must-be-explicitely-be-disposed – stuartd Mar 08 '23 at 12:09
  • 1
    See duplicates. As for who needs to dispose a disposable: that's up to you to decide _and_ enforce. If the rule is that the creator disposes, then other users shouldn't (though it usually doesn't hurt to dispose twice, but how does one know they're last?). Vice versa, if the last user knows they're last _and_ supposed to dispose, then they should (look at ASP.NET returning streams). Many stream-openers and -users have boolean parameters indicating whether they own the stream or should keep it open. – CodeCaster Mar 08 '23 at 12:12

0 Answers0