views:

142

answers:

5

I have a variable or array, which I no longer needed. How to destroy them? Sorry for noob-question.

+2  A: 

in .NET the Garbage Collector will do it for you ! But actually it may depend on what you mean when you write that you don't "need" your variable anymore

PierrOz
+11  A: 

You don't. Just let the reference go out of scope and it'll be automatically garbage-collected.

Dean Harding
thank you very much!
Alexry
+1  A: 

.NET has a built-in garbage collector. It is enough to stop referencing the array or variable when you don't need it. There is no need for an explicit destroy call.

Timores
+5  A: 

In .Net or any garbage collected language for that matter you simply release all references you hold to that object, and the garbage collector will eventually collect it Ex:

   int[] arr = new int[20];
   ....
   // when no longer needed set all references to null
   arr = null;
   // also creating a new object will release the old one automatically if there are no more references to it
   arr = new int[40]; // old array will be garbage collected

Also note that you don't need to do this every time, only when you explicitly want to release an object without releasing it's parent object or if the reference is a static field. Also releasing objects is not needed for local (method) variables only fields of classes or static fields.

Pop Catalin
thank you very much!
Alexry
Note that you don't need to set the reference to `null` either - the JIT/Runtime will conspire to figure out at what point the code will no longer use that reference; it's dead and collectable at that point. Google for `GC.KeepAlive()` descriptions on MSDN blogs and here on SO for details.
Michael Burr
@Alexry, your welcome, also just like @Michael Burr said, it's *extremely rare* in .Net to need to manually null out a variable, you usually don't need to do this.
Pop Catalin
A: 

Garbage-Collector is awsome, but the object is effectively destructed when the Garbage-Collector collects the objects not referenced anymore : later... So if you need the object to be disposed immediateli so that the destruct code is called, you shoule implement the IDisposable interface, and call the Dispose method before dereferencing your object.

Dargos