开发者

destruction of a variable or array in C#

I have a variable or array, which I no longer needed. How to destroy them? Sorry for noob-开发者_开发百科question.


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


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.


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜