Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disposing object in C#

Tags:

c#

.net

dispose

I have written the following class:

public class CoupleFrames
{
    public CoupleFrames(ColorImageFrame cif, Bitmap df)
    {
        this.colorFrame = cif;
        this.desktopFrame = df;
    }

    public ColorImageFrame colorFrame;
    public Bitmap desktopFrame;
}

Now I'm using the following code for disposing the variables.

CoupleFrames cf = new CoupleFrames(frame1, frame2);
// some code...
cf.colorFrame.Dispose();
cf.desktopFrame.Dispose();

I'm not sure that this is the correct way. Someone can suggest me the correct way for disposing the entire object?

like image 232
GVillani82 Avatar asked Dec 08 '22 14:12

GVillani82


1 Answers

I'm not sure that this is the correct way. Someone can suggest me the correct way for disposing the entire object?

Sure - you should make CoupleFrames implement IDisposable, and its Dispose method should dispose of the objects it "owns". For example:

public sealed class CoupleFrames : IDisposable
{
    private readonly ColorImageFrame colorFrame;
    private readonly Bitmap desktopFrame;

    public CoupleFrames(ColorImageFrame cif, Bitmap df)
    {
        // TODO: Argument validation, unless it's valid for these parameters
        // to be null, in which case the Dispose method would need to be careful.
        this.colorFrame = cif;
        this.desktopFrame = df;
    }

    public void Dispose()
    {
        colorFrame.Dispose();
        desktopFrame.Dispose();
    }
}

A few points to note:

  • You should make sure it's clear that the CoupleFrame really "owns" these constituent objects. Disposal relies on a clear ownership model
  • If CoupleFrame isn't sealed (and can't be) you may need to go into a more complicated pattern with virtual methods and finalizers. It can get very complicated, and you should read the advice given here by Joe Duffy et al. If your class is sealed, a lot of that complexity goes away
  • Public fields are generally a bad idea (in terms of encapsulation), which is why I've made them private here. I've also made them readonly, as if they can be changed later you need to think about whether changing them should dispose of the previously-referenced object etc.
  • By making CoupleFrame implement IDisposable, you're basically telling all clients that they should dispose of any instance they own. If you're not happy with imposing that burden, you need to rethink the design a bit.
like image 118
Jon Skeet Avatar answered Dec 11 '22 09:12

Jon Skeet