Sign in to follow this  
faculaganymede

C# garbage collector for ArrayList elements?

Recommended Posts

C# guru, In my application, I created an ArrayList and then tried to destroy specific elements in the ArrayList, as shown below. If I simply set an element to null, does the Garbage Collector (GC) automatically how to free the memory so there's no memory leaks? Is there a better way to destroy an element? I do not want to use the remove function, because I don't want to mess up the order of the other array elements (i.e. I need to keep their original index positions). Thanks.
// Creating my array list
public static ArrayList my_list = ArrayList.Synchronized(new ArrayList());

DATA_TYPE data = new DATA_TYPE(...);

my_list.Add(data);

// Some processes
...

// Destroying an element in the array list
DATA_TYPE ele_data = (DATA_TYPE)my_list[ele_i];
ele_data=null;  // Is there memory leak here?  Is GC taking care of this?

Share this post


Link to post
Share on other sites
That should be fine. You could also use a dictionary and use their "position" as the key.

EDIT: I answered your question without looking at your code... as Nypyren noted, you have to actually set the element to null. In your example, you copy the reference from the list to a new reference variable, then immediately set that new variable to a null reference... you still have a reference to the object in your list, though, so it won't be GC'd. You have to do what Nypyren showed you.

Share this post


Link to post
Share on other sites
Warning: the garbage collector does not automatically destroy the object when its last reference disappears. It generally destroys large numbers of unreferenced objects at the same time when the user requires more memory.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this