简体   繁体   中英

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]

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.

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 :

There is no need to delete the array, the GC will deal with it.

(Very) Simplistically:

When you run out of memory the garbage collector will kick in, stop your code and traverse all the live objects in memory.
live means some reference on the stack, a register, a static reference and some other things known collectively as 'GC Roots'. As it traverses them it notes that they are alive.

If your array is no longer live there is no way anything could access it anymore (that's what determines liveness) so the memory it occupied will be available for reuse.

There may be a reason to assign the reference to null if it would hold references alive longer than is desired or it is holding a large chunk of memory that you need immediately but this can easily backfire and actually make the array live longer. Instance rather than stack variables are better candidates for this optimisation if the containing instance will have considerably longer life than the array it contains.

To be clear, as a beginner you should not be considering this sort of thing, let the GC do it's job and only try to help it when you:

  1. know you need to
  2. know how to
  3. know how to check you did it right

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.

array = null, but I think it'll be a good idea if you read a little about the .NET memory management model to fully understand why.

Just to clarify in case you don't understand some of the terminology expressed in the other answers, GC stands for garbage collector. Languages like C# that have automatic memory management allow you to focus on doing what needs to be done and not worry about what you're creating and when to delete it. The GC works by periodically going through all of the objects you create and seeing whether they have any references to them. If not, this means there's no way you can do anything with them, so they might as well be deleted, and the system does just that.

For more details, see http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)

The array = null will suffice, no need for GC.Collect. You can check the memory before referencing to null you can it with Console.WriteLine(GC.GetTotalMemory), then check it again.

The closest you get is just to wait for it getting out of scope or setting it to null.

It won't remove or delete the array immediately, but after you drop all references to the array, the garbage collector (GC) will delete it in time...

You can declare and initialize your array in a if (true) {} statement, out of the if statement (after it) the array variable is not accessible, so it will be deleted then.

In C++ one can use the delete keyword. And it was originally mentioned in this comment and in other comments. The edit history shows this. This is a viable (albeit side answer) even if others do not understand why. I say this because one can use it to find their own elegant solution, if they understand more than one language.

In .NET/MSIL, you have the delete keyword, but it's called variablename .Dispose(). I'm offering this because it removes all references to the variable, and pushes it into a state of readiness for the garbage collection. Another option is to set the variable equal to null as that will keep the variable as a typed object, but release what it held to the garbage collection, so that it can be reassigned later.

Original Comment/Answer:

The garbage collection for C# is great and all, but sometimes you really need to remove a variable from memory and make a new instance of it, without some other part of your program keeping it alive. One has the ability to potentially place the existing chunk of memory held by the array into a GC state, by pointing the array at a new piece of memory, such as:

aMyArray = new int[];

The main problem that I can see with this way, however, is that you really do not want to waste a ton of memory, and then have everything come to a screeching halt as GC is started because the OS is freaking. I hold this thought, considering that C Sharp is now a mainstream language and is used in a LOT of different applications, including writing games... It'd truly be nice if C Sharp didn't act similar to ActionScript/FLASH in this respect.

This may have been solved but you could treat the array like a stack. Loop through it and pop the top off each iteration.

while(true)
{
    if(array.Length==0)
    {
        break;
    }
    array.Pop();
}

this way you can just push more values into the array without having to re-instantiate it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM