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.
List<int> mylist = new List<int>();
, then you are creating a new list ready to use. No need to clear it, it's ready to use, just access it through your variable (mylist
) that holds a reference to it. If you reassign the list (mylist = new List<int>();
), then the old list is no longer referenced by your code (if there are no other references to that list, then it's ready for Garbage Collection) and you create a new list. Yourmylist
variable now holds a reference to that new list, and it's ready to use in the same way.