Search code examples
c#disposegarbage-collectionfinalize

Do I need to implement a dispose or finalize in my objects?


For too long I let the garbage collector do its magic, removing all responsibilities from my self.

Sadly it never turned into an issue... So I never gave a second thought to the subject.

Now when I think about it I don't really understand what the "dispose" function really does and how and when it should be implemented.

The same question for finalize...

And a last question... I have a class pictureManipulation : when I need to save/resize/change format ... I start a new instance of that class use its objects and... well let the garbage collection kill the instance

class student
{
   public void displayStudentPic()
   {
      PictureManipulation pm = new PictureManipulation();
      this.studentPic = pm.loadStudentImage(id); 
   }
}

Class Test
{
  student a = new Student();
  a.displayStudentPic();
  // Now the function execution is ended... does the pm object is dead? Will the GC will kill it?
}

Solution

  • Regarding your class Student

    Do I need a Dispose() ?

    Assuming the Picture class is IDisposable: Yes. Because a Student object 'owns' the studentPic and that makes it responsible for cleaning it up. A minimal implementation:

    class Student : IDisposable
    {
       private PictureClass studentPic;
       public void Dispose()
       {
          if (studentPic != null)
            studentPic.Dispose();
       }
       ...
    }
    

    And you now use a Student object like:

    void Test
    {
      using (Student a = new Student())
      {
         a.displayStudentPic();    
      } // auto Dispose by using() 
    }
    

    If you can't/don't use a using(){} block, simply call a.Dispose(); when you're done with it.

    But please note that the (far) better design here would be to avoid keeping a picture object inside your Student object. That sets off a whole chain of responsibilities.

    Do I need a Finalizer?

    No. Because when a Student object is being collected, its studentPic object is guaranteed to be collected in the same run. A Finalizer (destructor) would be pointless but still expensive.