Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# clearing a list vs assigning a new list to existing variable

Tags:

c#

list

I am learning C#.

If I first make a variable to hold a list.

List<int> mylist = new List<int>();

Say I did some work with the list, now I want to clear the list to use it for something else. so I do one of the following:

Method 1:

mylist.Clear();

Method 2:

mylist = new List<int>();

The purpose is just to empty all value from the list to reuse the list.

Is there any side effect with using method2. Should I favor one method to the next.


I also found a similar question, Using the "clear" method vs. New Object I will let other readers decide what's best for their own use case. So I won't pick a correct answer.

like image 826
codenoob Avatar asked Sep 05 '25 03:09

codenoob


1 Answers

Using method 2 could result in unexpected behaviour within your program depending on how you are using the list.

If you were to do something like:

List<int> myList = new List<int> { 1, 2, 3 };

someObj.listData = myList;

myList = new List<int>(); // clearing the list.

the data in "someObj" will still be 1,2,3.

However, if you did myList.clear() instead, then the data in "someObj" would also get cleared.

An additional thought I just had. If you have dangling references to the original list, and reassign the variable using new in order to clear it, the GC will never clean up that memory. I would say it's always safer to use the .clear() method if you need to empty the contents of a list.

like image 190
CodeMonkey Avatar answered Sep 07 '25 21:09

CodeMonkey



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!