How to delete an array in c#?

I'm sorry if this is an obvious question but neither Google or a search here led me to an answer.

Is there a way to remove an array entirely?

I want the opposite of int[] array = new int[5]


Solution 1:

Say you call:

 void Foo(){
     int[] a = new int[5];
 }

In C# there is no way to undefine the variable a. That means a will be defined in Foo even if you set a to null. However, at the end of Foo a will fall out of scope. That means no code can reference it, and the garbage collector will take care of freeing the memory for you the next time it runs, which might not be for a long time.

Solution 2:

You just have to let it go out of scope, and wait for GC to find it; which might not be immediately (in fact, it almost certainly won't be). If you have a field on a long-lived object (that is going to stay in scope), then you can set to null, which can help.

You can influence the GC to collect sooner (not just your object: everything eligible), but you should rarely if ever do this. I use it only in test rigs; but:

GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); // DON'T DO THIS!!!

for more on GC.Collect:

  • What’s so wrong about using GC.Collect()?
  • When is it acceptable to call GC.Collect?

Solution 3:

You should read Chris Brumme's article on the subject; the first few paragraphs should explain the situation.

And anybody suggesting "assign null to the variable" should take particular note of the part that says:

Even if you add “aC = null;” after your usage of it, the JIT is free to consider this assignment to be dead code and eliminate it.