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?
When implementing the using keyword to instantiate an IO.StreamWriter object does that imply that
Share
The using keyword will call
Dispose. However, by convention,DisposeandCloseshould always perform the exact same functionality, and be interchangable.As such, any resource that is
IDisposablebut also provides aClose()method, such asStreamderived classes, are fine to use within ausingblock.This is addressed in the Framework Design Guidelines explicitly: “it is important that you make the
Closeimplementation identical toDispose“…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.”
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.