Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Keyword: .Close or .Dispose

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?

like image 442
Mike_OBrien Avatar asked Jan 16 '23 22:01

Mike_OBrien


2 Answers

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.

like image 110
Reed Copsey Avatar answered Feb 19 '23 13:02

Reed Copsey


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.

like image 27
Konrad Rudolph Avatar answered Feb 19 '23 11:02

Konrad Rudolph