Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i free objects in C#

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

like image 674
assassin Avatar asked Mar 09 '10 05:03

assassin


People also ask

How do I free a struct pointer?

free() is a function which takes in a pointer. &x is a pointer. This code may compile, even though it simply won't work. If we pretend that all memory is allocated in the same way, x is "allocated" at the definition, "freed" at the second line, and then "freed" again after the end of the scope.

Can you free a pointer in C?

It is safe to free a null pointer. The C Standard specifies that free(NULL) has no effect: The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation.

What happens when free in C?

free() just declares, to the language implementation or operating system, that the memory is no longer required.

How do you release an object in CPP?

When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.


3 Answers

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 :)

like image 122
Chris Avatar answered Oct 24 '22 06:10

Chris


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 implements IDisposable in a using statement.

like image 31
Mitch Wheat Avatar answered Oct 24 '22 04:10

Mitch Wheat


You do not. This is what a garbage collector does automatically - basically when the .NET runtime needs memory, it will go around and delete objects that are not longer in use.

What you have to do for this to work is to remove all linnks to the object.

In your case....

obj1=null;

at the end, then the object is no longer referenced and can be claimed from the garbage collector.

You can check http://en.wikipedia.org/wiki/Garbage_collection_(computer_science) for more details.

Note that if the object has references to unmanaged ressources (like open files etc.) it should implement the Disposable pattern (IDisposable interface) and you should explicitely release those references when you dont need the object anymore.

like image 8
TomTom Avatar answered Oct 24 '22 05:10

TomTom