Can anyone please tell me how I can free objects in C#? For example, I have an object:
Object obj1 = new Object();
//Some code using obj1
/*
Here I would like to free obj1,
after it is no longer required
and also more importantly
its scope is the full run time of the program.
*/
Thanks for all your help
It's not recommended, but if you really need to, you can force garbage collection via:
You don't have to. The runtime's garbage collector will come along and clean it up for you. That is why you are using C# and not unmanaged C++ in the first place :)
GC will collect all but unmanaged resources.
The unmanaged resources should implement
IDisposable
. If you are using an object that implementsIDisposable
, then you should either call the object'sDispose()
method when it is no longer needed or wrap its instance in ausing
statement.You can use the using statement. After the scope the reference to the object will be removed and garbage collector can collect it at a later time.
You don't have to. You simply stop referencing them, and the garbage collector will (at some point) free them for you.
You should implement
IDisposable
on types that utilise unmanaged resources, and wrap any instance that implementsIDisposable
in ausing
statement.As others have mentioned you don't need to explicitly free them; however something that hasn't been mentioned is that whilst it is true the inbuilt garbage collector will free them for you, there is no guarantee of WHEN the garbage collector will free it.
All you know is that when it has fallen out of scope it CAN be cleaned up by the GC and at some stage will be.