I have an array that works more or less like a hastable: based on an index, a value will be placed in the array, so some indices of the array will have values inside, others might not or will not. I have two pieces of code:
public void register( int index, string value )
{
_array[index] = value;
}
public void unregisterAll( )
{
/*
is this going to cause a memory leak when some of the values
are filled int the above function?
*/
_array = new string[12];
}
C# uses a garbage collector. If an object is no longer referenced it is (after some time) free'd automatically.
This is what happens (from the perspective of the garbage collector (GC)) when you execute unregisterAll()
object_array`1: referenced by _array
// execute unregisterAll();
create object_array`2 and let _array reference it
// Some time later when the GC runs
object_array`1: not referenced
object_array`2: referenced by _array
// Some time later, when the GC decided to collect
collect object__array`1
Note that this doesn't mean you cannot have a memory leak in C#. Some objects use unmanaged resources which need to be disposed manually (they implement the interface IDisposable which you can dispose of automatically by scoping it in a using block:
using(IDisposable disposable = new ...)
{
// use it
} // when leaving this scope disposable.Dispose() is automatically called
Or which you can dispose of manually by calling Dispose() on them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With