0

I have a complex objectA of type MyObject. I would like to create multiple variations of this MyObject based on a specific objectA.

public class MyObject()
{
    int myAttr1;
    string myAttr2;
    MyChildObject1 myChildObject1;
    MyChildObject2 myChildObject2;
    ...
}

public List<MyObject> createVariations(MyObject myObject)
{
    List<MyObject> myObjectList = new List<MyObject>();
    MyObject myFirstVariation = myObject;
    myFirstVariation.myAttr1 = myObject.myAttr1 + 5;

    myObjectList.Add(myFirstVariation);

    // TODO: Do different specific variations of the same source object!
    ...

    return myObjectList;
}

I know that this won't work because I am just creating multiple references to myObject and I am changing its parameters, so there will be lots of references of the same object in the list.

How would I get a list of objects with different configurations. Do I really have to create a copy constructor for these objects? Thank you in advance.

Ipsider
  • 553
  • 1
  • 7
  • 20
  • 1
    _"Do I really have to create a copy constructor for these objects?"_ - yes, or clone them: https://stackoverflow.com/questions/129389/how-do-you-do-a-deep-copy-of-an-object-in-net-c-specifically – CodeCaster Jul 19 '18 at 11:28
  • 1
    Of course, there are several ways to do this. One way is to serialise (using, say JSON.net) and then deserialise back to a new object. Performance might not be great, but if this is just for unit tests it may be acceptable. – Paul Suart Jul 19 '18 at 11:29
  • Thanks for your input – Ipsider Jul 23 '18 at 13:40

0 Answers0