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?
}
Regarding your
class StudentAssuming the Picture class is IDisposable: Yes. Because a Student object ‘owns’ the
studentPicand that makes it responsible for cleaning it up. A minimal implementation:And you now use a Student object like:
If you can’t/don’t use a
using(){}block, simply calla.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.
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.