Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disposable Using Pattern

Tags:

c#

  using (FileStream fileStream = new FileStream(path))
  {
    // do something
  }

Now I know the using pattern is an implementation of IDisposable, namely that a Try/Catch/Finally is set up and Dispose is called on the object. My question is how the Close method is handled.

MSDN says that it is not called, but I have read otherwise.

I know that the FileStream inherrits from Stream which is explained here. Now that says not to override Close() because it is called by Dispose().

So do some classes just call Close() in their Dispose() methods or does the using call Close()?

like image 602
Ty. Avatar asked Feb 04 '09 22:02

Ty.


People also ask

How can we implement disposable pattern?

Implement the dispose pattern A Dispose(bool) method that performs the actual cleanup. Either a class derived from SafeHandle that wraps your unmanaged resource (recommended), or an override to the Object. Finalize method. The SafeHandle class provides a finalizer, so you do not have to write one yourself.

What is IDisposable pattern in C# and how do you implement it?

For implementing the IDisposable design pattern, the class which deals with unmanaged objects directly or indirectly should implement the IDisposable interface. And implement the method Dispose declared inside of the IDisposable interface. We do not directly deal with unmanaged objects.

Does Dispose get called automatically?

Dispose() will not be called automatically. If there is a finalizer it will be called automatically. Implementing IDisposable provides a way for users of your class to release resources early, instead of waiting for the garbage collector.


2 Answers

The using statement only knows about Dispose(), but Stream.Dispose calls Close(), as documented in MSDN:

Note that because of backward compatibility requirements, this method's implementation differs from the recommended guidance for the Dispose pattern. This method calls Close, which then calls Stream.Dispose(Boolean).

like image 60
Jon Skeet Avatar answered Oct 02 '22 10:10

Jon Skeet


using calls Dispose() only. The Dispose() method might call Close() if that is how it is implemented.

like image 40
George Mauer Avatar answered Oct 02 '22 09:10

George Mauer