Jan-Niklas Schneider Jan-Niklas Schneider - 1 year ago 69
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

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

oldPersons = youngPersons;

After this block of code we would expect the list
to contain the data that was originally stored in
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
in a
-application both resulting in the same behavior on
Visual Studio Enterprise 2015 Update 3

Answer Source

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:


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:


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#?


Hope this helps...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download