The might Dispose()

wyrd

Senior Contributor
Joined
Aug 23, 2002
Messages
1,405
Location
California
The mighty Dispose()

Are there any general rules in knowing which objects that need to be explicitly Disposed (ie; objectInstance.Dispose())? I was under the odd impression that the GC would do it for me regardless when it reclaimed memory, aparently that may not be the case.
 
Last edited:
It should do it automatically eventually but for any object that has a Dispose method on it, you should call it when you're done with it. It's good practice and it also ensures unmanaged resources are freed in a timely manner.
 
I was reading up further on Dispose and its implementation, and ran across this;

Occasionally a domain-specific name is more appropriate than Dispose. For example, a file encapsulation might want to use the method name Close. In this case, implement Dispose privately and create a public Close method that calls Dispose. The following code example illustrates this pattern. You can replace Close with a method name appropriate to your domain.

http://msdn.microsoft.com/library/d.../en-us/cpgenref/html/cpconfinalizedispose.asp

Question;
Does this mean that if I use say, frm.Close() on a Form, or con.Close() on a SqlConnection, that I do not have to call Dispose, as that would be redundant? Or am I misunderstanding something here?
 
I would consult the documentation. For the Form class it says the Close method disposes it too, and the SqlConnection hints that it does but doesn't say so explicitly.
 
I think a modal form (with ShowDialog) does not call Dispose. You can Dispose of a modal form either by calling dispose in the modal form's Closed event, or in the opening form's code, after the ShowDialog line (after you've referenced everything you need from the modal form).

I'm pretty sure the Connection object will dispose when you call Close. There are only a handful of objects that support a Close method and I would bet that *most* of them will dispose of any resources they keep open (files, database connections, and forms are the three main ones).

-Nerseus
 
Good to know, thanks.

I think the biggest thing was that I was not aware that Close called Dispose implicitly until I started reading up on Dispose. I started thinking, "wait a minute, aren't I supposed to Dispose of outside resources?" then got all into this whole "when am I suppose to call Dispose?" thing.

Oh, and thanks for the heads up on the modal forms.
 
Back
Top