Search code examples
c#referenceicollection

ICollection ClearAndAddRange share reference?


I have two ICollection lists fullList and displayList.

private void method()
{
    if(condition != null) {
        displayList.Clear();
        if(fullList.Count() > 0)
        {
            displayList.ClearAndAddRange(
                           fullList.Where(x=>x.conditionID == condition.conditionID));

        }
    }

}

The problem I'm currently facing is whenever I update some value in displayList, fullList gets also updated . Is this expected behaviour?

What is the best way to modify it so that they won´t share references in between?


Solution

  • This is indeed expected behaviour. Consider the following two lists:

    var list1 = new[] { myObj1, myObj2 };
    var list2 = list1;
    
    list2[0].myProp = 3;
    

    where myObj1 and myObj2 are instances of MyClass.

    As list1 and list2 share the same references to the contained objects all modifications made to any of those items will be reflected in the other list also. When you want to avoid this behavioour you have to provide a deep-copy which will create an entriely new instance of your objects:

    var list2 = list1.Select(x => new MyClass { ... });
    

    For further information on deep cloning also see this post.