How Do I Dispose of an object

Im implementing copy and paste functionality in my windows MDI application.
Im using Visual Studio 2008 and programming in Visual C#

In the child window I have a "copy" menu item which does this.

((mainWin)(this.MdiParent)).copiedResults = new List<int>(theResults);

It basically copies a list of ints called "theResults" to a variable in the parent window.

Every time the user selects "copy" then the value of "theResults" should be copied to "copiedResults" in the parent window.

But every time the following is executed

((mainWin)(this.MdiParent)).copiedResults = new List<int>(theResults);

does this not create a new object? Wont I have lots of objects floating about eventually. Should I be doing something like;

if(((mainWin)(this.MdiParent)).copiedResults != null)
         Dispose(((mainWin)(this.MdiParent)).copiedResults);
((mainWin)(this.MdiParent)).copiedResults = new List<int>(theResults);

but Dispose(((mainWin)(this.MdiParent)).copiedResults);

throws an error

Any ideas how I can make this work?
rangers99Asked:
Who is Participating?
 
abelCommented:
> does this not create a new object?.

yes, the "new" instruction creates new object. But that happens all the time, and you should not worry about it. Object creation can be very cheap (depending on what's in the constructor of the object) and you should not worry about it.

Why you need a copy of the results, I don't know, but it is certainly not wrong. If you need to be safe on memory requirements, you can consider using a class variable on mainWin, which you can then set like this:

mainWin.currentResults = bla;

and that will be available to everybody. If you have only one mainWin ever, this is a simpler solution.

The Dispose part is not something that you need here. Dispose is meant for classes that implement IDispose, which is a story about resources that may stay around even after object destruction. Examples of that are streams and filewriters, for instance.
0
 
käµfm³d 👽Commented:
That's the beauty of managed languages--once there is no longer a reference to an object, the object is automatically cleaned up via the garbage collector. The only time you need to worry about cleaning up objects yourself is when you are dealing with unmanaged objects, such as opening files and I believe COM objects.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.