2

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

3
  • 2
    Can you define destroy? Commented May 12, 2016 at 16:51
  • 3
    Also, how do you know that it didn't work? Commented May 12, 2016 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. Commented May 12, 2016 at 16:58

2 Answers 2

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() { } } 
Sign up to request clarification or add additional context in comments.

6 Comments

There is nothing that OP mentioned in the question that requires to use IDisposable which is used usually for unmanged resources.
Correct , but since this is a very general question , a more general answer seemed appropriate
what should I put in the method?
freeing Unmanaged resources if you class uses any , or also writing to a log
What do you mean by saying unmanaged resources?
|
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.

8 Comments

this is not works for me
In what way doesn't it work? What behavior do you see after you set it to null that you're not expecting?
this is my code: Car c = new Car(); c = null; Console.ReadLine();
Yes, that code should work fine. The GC should destroy the object. Why do you think it's not working?
@D4NieLDev - What did you try that made you think it didn't work?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.