3

This is a very basic question, but I thought better to ask. Let us assume I have the following code snippet.

List<String> mystringlist1 = new List<String>();

List<String> mystringlist2 = new List<String>();
mystringlist2.Add("hello1");
mystringlist2.Add("hello2");
mystringlist2.Add("hello3");

//Now I assign the second list to first list
mystringlist1 = mystringlist2;

Now as it stands, both the lists will be pointing to the same memory location and trying to access the individual elements will result in the same elements of the above list.

If so,

  • what would have happened to the unclaimed/unused allocation which was done for mystringlist1?
  • Will this be automatically garbage collected or will it result in memory leaks?
  • Is it a bad practice to do this?
0

2 Answers 2

3

What you're doing is perfectly fine. In fact, that's the scenario the language and the runtime was designed to handle. You don't explicitly allocate and free memory. Instead you create instances and once these are no longer used the garbage collector will reclaim the associated memory.

As you assign mystringlist1 = mystringlist2 the instance that mystringlist1 pointed to becomes eligible for garbage collection. It means that if a garbage collection is triggered the memory will be reclaimed.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Both yours as well as Bradley's were good answers. But I could select only one as answer & upvoted yours.
2
  1. It will be garbage collected
  2. Yes it is automatic
  3. Yes it is bad practice to allocate something you never use. If you are going to use it for something, allocate and reassign away. There is no reason to randomly instantiate stuff though.

Note that it will be collected on the next pass of the Garbage Collector for its generation. Since it wasn't around very long, it should still be in Gen0 and be collected fairly quickly. This isn't true for all variables, so it may look like there is a memory leak when there really isnt.

The other exception is anything that uses unmanaged memory (like Bitmap) which need to be disposed after use.

1 Comment

Would the downvoter care to comment what problem you had with my answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.