Zone2Risk
Zone2Risk

Reputation: 13

The parameters of the objects in my list change even if I clone the list

Good morning,

I make a software that creates steps from the above and adds them to a common list.

Here's my code:

        List<List<Crêpe>> Solutions = new List<List<Crêpe>>(); 
        Solutions.Add(new List<Crêpe>(Ordre)); // 1.

        for (int i = NombreMax; i > 0; i--)
        {
            Ordre.Reverse(0, positionDuNombreAChercher); // 2.

            for (int n = 0; n < positionDuNombreAChercher; n++)
            {
                Ordre[n].FaceCraméBienPlacé = !Ordre[n].FaceCraméBienPlacé; // 3.
            }

            Solutions.Add(new List<Crêpe>(Ordre)); 

        }

I've put some markers to explain my problem to you:

In 1, I clone my list and add it in "Solution".

In 2, I reverse the "Ordre" list, which no longer has a link with the list I cloned because it is a clone and therefore the changes are not made in "Solution".

In 3, you can see I'm changing the parameters of the object in "Ordre". That's where the error happens! So I change my parameters in the object and my list that I clone is not supposed to change it's parameter's object because it was cloned but the problem is that the list that I cloned at the beginning to also change these object parameters.

to note: She changed her settings but not her order, as step 3 does with this list.

I'm really sorry if that wasn't clear, if you want a better explanation tell me.

Thank you for helping me :)

EDIT : Here is the object :

internal class Crêpe
{
    internal int Nombre { get; set; }
    internal bool FaceCraméBienPlacé { get; set; }

    public Crêpe(int position, bool faceCraméBienPlacé)
    {
        Nombre = position;
        FaceCraméBienPlacé = faceCraméBienPlacé;
    }
}

Upvotes: 0

Views: 24

Answers (1)

Sweeper
Sweeper

Reputation: 272845

You copied the list, but you didn't copy the crêpes!

To copy the crêpes, you can write a GetCopy method in the Crêpe class:

public Crêpe GetCopy() => new Crêpe(Nombre, FaceCraméBienPlacé);

And then use Select to create a copy of each Crêpe, then use ToList to create a new list:

Solutions.Add(Ordre.Select(x => x.GetCopy()).ToList()); // 1.

You should also change the last line in the outer loop.

Upvotes: 1

Related Questions