Click here to Skip to main content
15,891,657 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to create a Dispose() inside a simple class ?

What I have tried:

C#
    public class Hero  // this is a simple class
    {
       public void Initialize()
       { 
           imgHero = Bitmap.FromFile(root + "spaceshipHero1.png");
       } 

       Image imgHero;
       string root = @"D:\Programe\Info\Visual Studio 2010\Projects\Game\Shoot-em\Shoot-em\bin\Debug\";
       int Width = 80; int Height = 90;
     

       public int X = 50;
       public int Y = 50;


       public void canvas_Paint(object sender, PaintEventArgs e)
       {
           e.Graphics.DrawImage(imgHero, new Rectangle(X, Y, Width, Height));
       }
       public void Pozition(int x, int y)
       {
           X = x; Y = y;
       }
       public void Resize(int width, int height)
       {
           Width = width; Height = height;
       }
     
       public void Dispose()
       {
// what is the code here that Garbage collector will clean this object efficiently?
// ex:Hero hero = new Hero();<new object  hero.Dispose();<clean new object
       }

    }
Thank you.
Posted
Updated 17-Mar-20 4:33am
v2

1 solution

Use IDisposable

IDisposable Interface (System) | Microsoft Docs[^]

You'll probably want to do "imgHero.Dispose();" in your Dispose method. The only other things you are referencing don't need to be disposed.
 
Share this answer
 
Comments
_Q12_ 17-Mar-20 10:59am    
I copied that long code into my Hero class and changed
// The class constructor.
public Hero(IntPtr handle)
and
~Hero()

BUT, now when I create the object:
public Hero hero = new Hero();
expects an "IntPtr handle" for the new Hero(); part
screenshot: https://i.imgur.com/6nTB9dc.png
_Q12_ 17-Mar-20 11:10am    
ok, i read your sugestion and I think this is your solution, right?

public void Dispose()
{
imgHero.Dispose();
}
Your "imgHero.Dispose();" is very good trick!
I didnt use it so far like that or any other ways.
_Q12_ 17-Mar-20 11:16am    
Still NOT GOOD answer !
I want to get rid of the object itself, after creation !!!
New object, object.Dispose !!!!
If i make 1000 objects, I want to clean them and their properties from Form1 where i create them.
_Q12_ 17-Mar-20 11:42am    
Now i clarified the issue, and you helped.
Thank you.

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