If I have a class like
public class Foo
{
private Image image;
....
....
}
should I create destructor and call Dispose there to free the image's memory or the DC will do it automatically.
If I have a class like
public class Foo
{
private Image image;
....
....
}
should I create destructor and call Dispose there to free the image's memory or the DC will do it automatically.
Check out the Dispose pattern as proposed by Microsoft. The first DO in the article states: implement the Basic Dispose Pattern on types containing instances of disposable types. See the Basic Dispose Pattern section for details on the basic pattern.
Since Image is a disposable type you should implement IDisposable on the wrapping class.
I wouldn't bother with destructors, since it might take a while before the object gets destructed, while with Dispose you maintain control.
You can implement IDisposable:
public class Foo : IDisposable
{
private Image image;
public void Dispose()
{
if (image != null)
{
image.Dispose();
image = null;
}
}
}
Then Usage:
using(var f = new Foo())
{
} // disposed automatically
The primary use of this interface is to release unmanaged resources. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams.