Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep Copy a BindingList<Object>

Tags:

c#

I don't understand how to make a clone of a BindingList<Object>.

I want to create a new copy of an existing list that does not share the same reference. Another complication is that my object itself contains a nested BindingList<Object>.

I tried the constructor method:

BindingList<Equation> NewEquationList = 
                         new BindingList<Equation>(OldEquations.ToList());

I then tried looping through the list, setting the new values:

BindingList<Equation> NewEquationList;
foreach (Equation OldEquation in OldEquations)
{
    Equation NewEquation = new Equation()
    {
        NewEquation.ID = OldEquation.ID,
        ...
    };
    NewEquationList.Add(NewEquation);
}

I tried implimenting a 'Copy Constructor' - I still don't understand how that differs from the above but it also didn't work.

I tried setting my Equation class as [Serializable] and serializing/deserializing the object however I receive an error stating that the PropertyChangedEventHandler used in my class is not marked as Serializable.

I didn't think making a value copy of a reference type would be a complicated procedure, however I am having difficulty in making this work.

What should I do?

EDIT:

My solution was to add a Clone method into the Equation's class. I still don't understand why this worked and the 'Copy Constructor' did not.

public Equation Clone()
{
    Equation NewEquation = new Equation();
    NewEquation.ID = this._ID;
    ...

    //Nested BindingList:
    NewEquation.EquationVariables = new BindingList<EquationVariable>  
            (this._EquationVariables.Select(EV => EV.Clone()).ToList());

    return NewEquation;
}

Using the above, the following successfully created a deep copy:

NewEquationList = new BindingList<Equation>
        (OldEquations.Select(E => E.Clone()).ToList());
like image 471
Robert Avatar asked Oct 15 '25 13:10

Robert


1 Answers

Do your objects (elements in the BindingList) implement ICloneable? If so then look into using ICloneable.Clone method then clone each object manually when creating a new list.

Your IList use i.e.

BindingList<Equation> NewEquationList = 
                     new BindingList<Equation>(OldEquations.ToList());

Just creates a copy with the same references (shallow copy).

If the objects (elements in the BindingList) are serialisable...

Have a read of this SO post… especially "Serialize the object then de-serialise to get a deep cloned non referenced copy".

Often the best if not the only way to deep copy collections is to do the serialise then deserialise dance.

like image 174
Paul Zahra Avatar answered Oct 18 '25 08:10

Paul Zahra



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!