Click here to Skip to main content
15,892,072 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have to reformulate my question:
I have a simple class named Hero, and it contain some public variables and an event.
It's very basic class.

In Form1, I create an object from that class:
public Hero hero = new Hero();
Now, i want to destroy that object. How to destroy it?

What I have tried:

You can see the code here:
My Hero class [^]
Posted
Updated 17-Mar-20 5:34am
v3

1 solution

Three ways:
1) Delete all references to it by overwriting each and every variable which refers to the instance you want to get rid off and wait. At some point the Garbage Collector will get called in, and will Dispose of it for you automatically (or your app will end first)
C#
myVariable = null;
2) Manually call Dispose on the instance you want to get rid of:
C#
if (myVariable != null)
   {
   myVariable.Dispose();
   myVariable = null;
   }
3) Create the instance at the start of a using block, and the system will automatically call Dispose for you when the variable goes out of scope:
C#
using (MyType myVariable = new MyType())
   {
   .. use myVariable here ...
   }
 
Share this answer
 
Comments
_Q12_ 17-Mar-20 11:41am    
I understand now, thank you very much.
OriginalGriff 17-Mar-20 11:48am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900