Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I call Dispose() within a function after Return?

Should I call .Dispose() after returning an object that implements IDisposable?

myDisposableObject Gimme() {
  //Code
  return disposableResult;
  disposableResult.Dispose();
}

In other words, is the object I return a copy, or is it the object itself? Thanks :)

like image 625
Camilo Martin Avatar asked May 14 '10 09:05

Camilo Martin


People also ask

Does Dispose get called automatically?

It's essential to keep in mind that IDisposable relies on the programmer to call the “Dispose” method as the runtime will not automatically call it. IDisposable is just a pattern to enable us to release resources deterministically when they are no longer needed.

How do I call a Dispose method?

A protected override void Dispose(bool) method that overrides the base class method and performs the actual cleanup of the derived class. This method must also call the base. Dispose(bool) ( MyBase. Dispose(bool) in Visual Basic) method passing it the disposing status ( bool disposing parameter) as an argument.

Does using statement Call dispose?

The using declaration calls the Dispose method on the object in the correct way when it goes out of scope. The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned.

What does dispose method do with?

Dispose improves performance and optimizes memory by releasing unmanageable objects and scarce resources, like Graphics Device Interface (GDI) handles used in applications with restricted Windows space. The Dispose method, provided by the IDisposable interface, implements Dispose calls.


2 Answers

It's the object itself. Don't call Dispose here, even if you reverse the order so that it gets called.

like image 171
Marcelo Cantos Avatar answered Oct 20 '22 00:10

Marcelo Cantos


One thing that none of the answers so far have mentioned is that you should dispose the object if Gimme() throws an exception. For example:

MyDisposableObject Gimme() 
{
    MyDisposableObject disposableResult = null;
    try
    {
        disposableResult = ...

        // ... Code to prepare disposableResult

        return disposableResult;
    }
    catch(Exception)
    {
        if (disposableResult != null) disposableResult.Dispose();
        throw;
    }
}
like image 32
Joe Avatar answered Oct 20 '22 00:10

Joe