MikeD MikeD - 2 years ago 92
C# Question

what happens to memory when reassign array in C#?

In the following code, what happens to the memory myArray initially pointed to once it's reassigned in the 2nd line? Is that memory lost, or does the C# garbage collector take care of it?

static void Main(string[] args)
double[] myArray = new Double[10];
myArray = new Double[3];

As far as I've been reading, there's no way to explicitly free up the memory, so I'm hoping C# automatically does it.

Answer Source

When your variable goes out of scope and the memory is no longer required then it becomes eligible for garbage collection.

MS explains all, as seen here: https://msdn.microsoft.com/en-us/library/aa691138(v=vs.71).aspx

C# employs automatic memory management, which frees developers from manually allocating and freeing the memory occupied by objects.

Automatic memory management policies are implemented by a garbage collector. The memory management life cycle of an object is as follows:

  1. When the object is created, memory is allocated for it, the constructor is run, and the object is considered live.
  2. If the object, or any part of it, cannot be accessed by any possible continuation of execution, other than the running of destructors, the object is considered no longer in use, and it becomes eligible for destruction. The C# compiler and the garbage collector may choose to analyze code to determine which references to an object may be used in the future. For instance, if a local variable that is in scope is the only existing reference to an object, but that local variable is never referred to in any possible continuation of execution from the current execution point in the procedure, the garbage collector may (but is not required to) treat the object as no longer in use.
  3. Once the object is eligible for destruction, at some unspecified later time the destructor (Section 10.12) (if any) for the object is run. Unless overridden by explicit calls, the destructor for the object is run once only.
  4. Once the destructor for an object is run, if that object, or any part of it, cannot be accessed by any possible continuation of execution, including the running of destructors, the object is considered inaccessible and the object becomes eligible for collection.
  5. Finally, at some time after the object becomes eligible for collection, the garbage collector frees the memory associated with that object.

If you want to go into more detail then you can look here: https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/index

or I'm sure you can also find some blogs on the topic.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download