locked
How to destroy an object in C#? RRS feed

  • Question

  • 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.

    Monday, June 19, 2006 8:05 AM

Answers

  • 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

     

    Monday, June 19, 2006 8:09 AM
  • 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

    Monday, June 19, 2006 3:44 PM

All replies

  • You can use Control.Dispose().
    Monday, June 19, 2006 8:09 AM
  • 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

     

    Monday, June 19, 2006 8:09 AM
  • That's not remotely analagous to 'object = nothing'. 

     

    Monday, June 19, 2006 8:10 AM
  • Get it!

    Thank you very much!

     

     

    Monday, June 19, 2006 8:34 AM
  • 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

    Monday, June 19, 2006 3:44 PM
  • BigCannon bc = new BigCannon();

    bc.target(object);

    bc.fire();

    Tuesday, June 20, 2006 8:16 AM
  • haha, funny one XD
    Friday, May 28, 2010 6:40 PM