1

How to destroy an object in a condition? for example:

Car c = new Car()
if (something)
//destroy car

I have tried to set the object to null but it didn`t work...

D4NieLDev
  • 260
  • 1
  • 3
  • 14
  • 2
    Can you define `destroy`? – Yacoub Massad May 12 '16 at 16:51
  • 3
    Also, how do you know that it didn't work? – Yacoub Massad May 12 '16 at 16:54
  • 1
    @Erik Philips - Not sure why this was marked as a duplicate. This question doesn't ask about IDisposable. Furthermore, IDisposable does not destroy the object, it just allows cleaning up of resources, so the other question doesn't answer this question at all. – RJM May 12 '16 at 16:58

2 Answers2

2

In addtion to setting your object as null , you should also remove it from other objects which refrences it as well if you class uses resources that needs to be freed up use IDisposable

public class Car: IDisposable
{
    // free resources
    public void Dispose()
    {

    }
}
Shachaf.Gortler
  • 5,655
  • 14
  • 43
  • 71
1

set c = null; As long as there are no other references to it, the garbage collector will destroy it the next time it runs.

RJM
  • 1,164
  • 9
  • 21