Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# allocate memory and assign a different variable

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?
like image 733
Muthu Avatar asked Nov 25 '25 20:11

Muthu


2 Answers

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.

like image 193
Brian Rasmussen Avatar answered Nov 28 '25 10:11

Brian Rasmussen


  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.

like image 32
BradleyDotNET Avatar answered Nov 28 '25 09:11

BradleyDotNET



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!