Jan-Niklas Schneider Jan-Niklas Schneider - 14 days ago 7
C# Question

C# Bug!? Clearing and assigning two lists of the same type. Both empty afterwards

Let's say we have two lists of the object

Person
, such as
oldPersons
and
youngPersons
. Both lists have different objects stored in them. The issue happens in following code:

oldPersons.Clear();
oldPersons = youngPersons;
youngPersons.Clear();


After this block of code we would expect the list
oldPersons
to contain the data that was originally stored in
youngPersons
but what can be observed while debugging is that both lists are empty.

Did anyone ever encounter this bug(!?)?. I cannot explain this behavior at all.
I tried this on .net versions
4.5.2
and
4.6.2
in a
WPF
-application both resulting in the same behavior on
Visual Studio Enterprise 2015 Update 3
.

Answer

This is not a bug... this is expected behavior. It comes down to "what" you assign. To make it clear, let me explain what is happening in your example, though I will not use the 100% technically accurate explanation for the purposes of clarity:

1st you are creating two new lists.

List<Person> youngPersons = new List<Person>();
List<Person> oldPersons = new List<Person>();

What this is doing is creating two "containers" to hold your respective lists.

When you add items to the list, you are effectively putting items into the respective containers.

youngPersons.Add(new Person("Tom"));
oldPersons.Add(new Person("Frank"));

Now, when you "clear" one of the lists:

oldPersons.Clear();

You have made the "oldPersons" container empty. But here is where your misunderstanding comes in, when you do this:

oldPersons = youngPersons;

What you are doing is assigning the "youngPersons" container, to the oldPersons container. This is making both variables point to the same container at this point. The original "oldPersons" container is no longer has any reference to it.

Therefore, when you do the:

youngPersons.Clear();

You are actually clearing both youngPersons, and oldPersons at the same time, since they are pointing to the same "container".

What I suspect you really want to do is "copy" the list, and have it used for later. I won't go into ton of details on this here, since you can do a quick google search to find out how. But here are a few links that you might find useful: How do I clone a generic list in C#?

http://www.c-sharpcorner.com/UploadFile/mahesh/how-to-copy-a-C-Sharp-list/

Hope this helps...