Reputation: 27350
I have seen examples of objects which are automatically disposed through the 'using' statement, which is a definitive way of defining the scope of the object and forcing a dispose.
I've also seen dispose called in the finally of a try/catch/finally block.
However, say the disposable object is instantiated as a property initializer in a form class how do I ensure that Dispose is called in that scenario?
Upvotes: 1
Views: 179
Reputation: 1283
make you're class inherit from IDisposable than use using(var myclass=new myclass()) {} Hope this helps you.
Upvotes: 0
Reputation: 44285
There are various techniques to accomplish this task depending on your needs. From MSDN:
When a form is closed, all resources created within the object are closed and the form is disposed.
If the lifespan of the property is directly tied to the form, then you can Dispose of the object in the overridden Dispose method in the designer file. So when you call form.Close()
, the Disposable object will be disposed of as well.
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
myDisposableObject.Dispose();
base.Dispose(disposing);
}
This particular part of the designer file is safe from being over-written, However, developers may overlook the designer file assuming auto-generated code. Another means of disposal such as hooking into the dispose event of the Form may be more appropriate to your needs.
Upvotes: 1
Reputation: 62504
If you mean something like this:
var form = new Form { Dependency = new DisposableDependency() };
then Form
class should dispose it in own Dispose()
method, the best way would be implement own IDisposable
as well or dispose such disposable dependencies in Close()
method if such exists.
Upvotes: 1
Reputation: 5165
You can get the Form to implement IDisposable and just call the Dispose() method on your object in your Form.Dispose()
Upvotes: 0