How to destroy an object in C#?

I created an object using "new" method from a class. After some operation, I need to explicitly destroy this object. In vb the code is simply "object=nothing".

But in C#, i don't know how to do that. Thks.




Answer this question

How to destroy an object in C#?

  • Bobasaurus

    BigCannon bc = new BigCannon();

    bc.target(object);

    bc.fire();


  • Moorstream

    Get it!

    Thank you very much!



  • Moritz Kroll

    You can dereference an object using

    obj=null;

    in C#

    Then you can force Garbage Collection using

    GC.Collect();

    Of course it is not recommended to do so



  • squ1die

    That's not remotely analagous to 'object = nothing'.



  • PMKern

    You can use Control.Dispose().


  • brigitte

    Actually, object = nothing does not delete it at all. object = null; will do what object = nothing does in VB.NET, which is to discard the reference to it, which will speed up when it will be cleaned up by the garbage collector, but you can't know when that will be.

    If an object has a Dispose() method, you need to call it before it goes out of scope. You can use the using keyword to do this for you automatically

    using (Graphics gr = Graphics.FromBitmap(bm))

    {

    // do stuff

    }// gr.Dispose() is called here



  • How to destroy an object in C#?