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
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.
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.
free() just declares, to the language implementation or operating system, that the memory is no longer required.
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.
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 :)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With