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 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.
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.
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