Tag and Object


I`m using C# .Net 3.5 VS 2008

Lets say I assign the Tag property of an object to a custom object, if I destroy the object the custom object should also be destroyed right?

For example : I assign a Custom Object - CarObj to a Treeview Node.

TreeNode.Tag = CarObj;

If I remove the TreeNode, the CarObj should also be removed right? From what I see CarObj still exists, How do I solve this issue?
Who is Participating?
Jacques Bourgeois (James Burger)Connect With a Mentor PresidentCommented:
One thing that everybody forgot here, including me, is that objects are not actually "destroyed" when we get rid of them. The reference (variable, pointer) is destroyed, but the memory is not reclaimed.

.NET memory cleaning is managed by the garbage controller, an important piece of the framework. Setting an object to Nothing simply breaks the link between the variable and any reference. When all those links have been broken, the garbage collector knows that the object is not used any more and that the memory it takes is available if needed.
Obadiah ChristopherConnect With a Mentor Commented:
The CarObj should not be removed.

Consider this.

You have a datatable and you assign it as a datasource to the gridview.

Now if you set the datasource of gridview to null or delete a row from gridview it won't affect the datatable. right?
San24Author Commented:
Thanks infomaniac. The issue is resolved.

I got confused, I have assigned objects to items in dictionary before and when i remove the entry the object ceases to exist.
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

käµfm³d 👽Connect With a Mentor Commented:
The CarObj should not be removed.
I have to disagree slightly. If the Tag property is the only reference to the CarObj, then the CarObj would be eligible for garbage collection once the TreeNode is destroyed.
Jacques Bourgeois (James Burger)Connect With a Mentor PresidentCommented:
The object will be destroyed when all references are destroyed. That means that you need to get rid of both the Tag property (or the Node or the TreeView), and the variable CarObj, as well as any other reference that could have been made to that object.

If any reference "lives", then the object won't be destroyed.
San24Author Commented:
@Kaufmed - Doesn`t Node.Remove() destroy the TreeNode?

Getting rid of the TreeView is not an option. But I resolved this issue by casting the Tag as an object and removing it. Let me know if you are interested in the solution.
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.