-1

Good morning,

I've noticed that when you assign a list as a parameter to an object and then make changes to it, the object's parameter also changes its value.

I would like to know how to avoid this and how to delete my list without affecting my object.

Reconstruction :

            List<string> images = new List<string>
            {
                "1",
                "2",
                "3"
            };

            Message messageA = new Message(objet, rtfMessage, images, date_de_publication, texteEtat, couleurEtat);
            // messageA.images = 1 , 2 , 3

            images.Clear();
            // messageA.images = new List<string>()

Thanks

EDIT

Here's a solution I found, but it's not very optimized;

            string[] vs = images.ToArray();
            Message message = new Message(objet, rtfMessage, vs.ToList(), date_de_publication, texteEtat, couleurEtat);
  • 2
    You have to create a copy of list for, have a look at this thread [How create a new deep copy (clone) of a List](https://stackoverflow.com/questions/14007405/how-create-a-new-deep-copy-clone-of-a-listt) – Pavel Anikhouski Jan 04 '20 at 13:42
  • You would have to add the item to different parent to prevent it from getting deleted. A child will not get deleted if it is linked to more than one parent. – jdweng Jan 04 '20 at 13:52
  • Check my answer [link](https://stackoverflow.com/questions/59591212/detaching-a-list-from-an-object/59591784#59591784) – Binara Thambugala Jan 04 '20 at 14:53

2 Answers2

1

Please do like below

new List<string>(images)
List<string> images = new List<string>
{
     "1",
     "2",
     "3"
};

Message messageA = new Message(objet, rtfMessage, new List<string>(images), date_de_publication, texteEtat, couleurEtat);
// messageA.images = 1 , 2 , 3

images.Clear();
// messageA.images = new List<string>()
0

You could create a clone of the List<string> and pass it as parameter. For example,

var clonedImage = images.Select(item => (string)item.Clone()).ToList();

Now you could pass the clone as

Message messageA = new Message(objet, rtfMessage, clonedImage , date_de_publication, texteEtat, couleurEtat);
Anu Viswan
  • 17,797
  • 2
  • 22
  • 51