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?
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:
CoupleFrame
really "owns" these constituent objects. Disposal relies on a clear ownership modelCoupleFrame
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 awayCoupleFrame
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With