Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dispose()

Status
Not open for further replies.

kyledunn

Programmer
Jan 2, 2001
145
US
The code below was inserted by the forms designer. The components variable was set to null also by the forms designer. I saw no reason to override the Dispose method in this fashion because unless the components variable is not null it would do exactly what I think the regular Dispose method would have been doing. Can anyone explain how this relates to components and if it is reasonable to delete it?

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if( components != null )
components.Dispose();
}
base.Dispose( disposing );
}

Kyle
 
It depends on whether or not your object (or one of it's parents) implements the IDisposable interface. If it or they do, then you'll have to leave the code there. The fact that the boiler-plate code is calling &quot;base&quot; is a good indication that this is so.

Otherwise, it's a good convention to have a Dispose() method so that users of your class can call it when they are finished with your object. This allows you to clean up expensive resources, rather than waiting for the garbage collector to get around to it.

You can also use the Finalize method to ensure things get disposed of:
Code:
public void Dispose()
{
   //
   // Clean up resources first
   //
   // Then tell GC not to call finalize
   GC.SuppressFinalize(this);
}
   
protected override void Finalize()
{
   //
   // Clean up resources first
   //
   // Then call base classes Finalize method.
   base.Finalize();
}
That way if a user calls Dispose, things get cleaned up, and the garbage collector won't call the Finalize method (which would try and clean them up a second time). If the user forgets to call Dispose, when the GC gets around to cleaning the instance up, it calls the Finalize method (which cleans things up), and you aren't leaking resources.

Chip H.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top