jenni-mm2
jenni-mm2

Reputation: 305

List<T> copied from same object, properties updated in both places

I've done a lot of reading on copying/cloning objects in C# and I was trying to work from this example, but my situation is a little different.

I have a list of question/answer pairs being returned from the database. I want to use that to create two lists for parent and child objects. When I do that, any changes I make to the child are reflected in the parent.

I've tried several permutations of creating new lists, cloning, etc, but always end up with the same result.

List<QuestionVM> questionlist = productRepository.GetQuestions();
parent.Questions = AddQuestions(true, parent, questionlist);
child.Questions = AddQuestions(false, child, questionlist);

private List<QuestionVM> AddQuestions(bool parent, Line line, List<QuestionVM> questions)
{
    //shouldn't this create a new object, not just a reference?
    List<QuestionVM> qs = new List<QuestionVM>(questions);

    if (parent)
    {
        return qs.Where(w => w.ShowOnParent).ToList();
    }
    else
    {
        return qs.ToList(); 
    }
}

Any help is greatly appreciated.

Upvotes: 1

Views: 474

Answers (2)

Seblic
Seblic

Reputation: 1

If anyone else is still interested in this. You can use automapper to make deepcopy of an object.

Upvotes: 0

Eugene Podskal
Eugene Podskal

Reputation: 10401

It is not enough to just create copy of the list, because items in both old and new lists will still refer to the same objects.

You need to implement ICloneable interface(or just your own custom method) for your objects and call clone for each original object while creating copy list:

public class QuestionVM: ICloneable
{
     public Object Clone()
     {
          return new QuestionVM(this.prop1, this.prop2);
     }
}

...

private List<QuestionVM> AddQuestions(bool parent, Line line, List<QuestionVM> questions)
{
...
return qs
    .Where(w => w.ShowOnParent)
    .Select(obj => (VMQuestion)obj.Clone())
    .ToList();
...
}

P.S.: If VMQuestion contains fields of other complex types then they have to provide Clone method as well.

Upvotes: 2

Related Questions