When implementing the using
keyword to instantiate an IO.StreamWriter
object does that imply that .close
is called on the object or .dispose
? Or does it matter since once it hits the end using it is out of scope and will be garbage collected anyways?
The using keyword will call Dispose
. However, by convention, Dispose
and Close
should always perform the exact same functionality, and be interchangable.
As such, any resource that is IDisposable
but also provides a Close()
method, such as Stream
derived classes, are fine to use within a using
block.
This is addressed in the Framework Design Guidelines explicitly: "it is important that you make the Close
implementation identical to Dispose
"...
The MSDN help for IDisposable also suggests this: "The implementer of a class that has such a convention might choose to implement a public method with a customized name, such as Close, that calls the Dispose method."
Or does it matter since once it hits the end using it is out of scope and will be garbage collected anyways?
It will not be garbage collected - after it is no longer in scope, and no longer referenced by any objects, it will be eligible for garbage collection. This means that it will (at least if written properly), eventually get cleaned up, but it may not happen for a long time - including not until the program terminates. The using block causes the resource (not the memory), such as the stream, to be closed immediately.
Using
only calls Dispose
at the end of the scope. However, for classes such as StreamWriter
, Dispose
ends up calling Close
internally.
Or does it matter since once it hits the end using it is out of scope and will be garbage collected anyways?
This is a misconception: the whole reason for the Using
block and the Dispose
method is that an object is not garbage collected immediately at the end of the scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With