0

My program class has:

Application.Run(new Form1());

in form1 class I have:

model = new Model(this);
modelarray myArray = new modelarray(this);
model = myArray.models[0];
myArray.models[1] = (Model) model.Clone();

    private void btn13_Click(object sender, EventArgs e)
    {
        model.btn13Clicked();
    }

    private void btnGetBackClone_Click(object sender, EventArgs e)
    {
        model = myArray.models[1];
        //here I'm expecting to get the original object back (ie. with btns[7,7].Visible = True) but it doesn't work!!
    }

in model class I have:

private Button[,] btns;

public Model(Form1 form1)
{
btns = new Button[10,10];
myform = form1;
btns[8, 6] = form1.btn1;
btns[9, 5] = form1.btn2;
btns[7, 7] = form1.btn13;

}

public void btn13Clicked()
{
   btns[7, 7].Visible = False;
}

public object Clone()
{
  return this.MemberwiseClone();
}

in modelarray class I have:

public Model[] models = new Model[19];
public modelarray(Form1 form1)
{
  models[0] = new Model(form1);
}

Note my comment under the btnGetBackClone_Click method. "//here I'm expecting to get the original object back (ie. with btns[7,7].Visible = True) but it doesn't work!!"

I understand that this is because models[0] and models[1] are pointing to the same memory location (ie copy by ref). But I am really lost at how to implement a solution in this situation. Searches on 'deep copy' did not seem to help as serializing a form didn't work. Can someone please correct my cloning error?

I know I could simply redo "btns[7, 7].Visible = True;" but I would like to know a cloning solution so it will copy all future fields I decide to put in my model.

I've had a search on codeproject.etc but there doesn't seem to be any straightforward intro to winforms.

toop
  • 10,834
  • 24
  • 66
  • 87

1 Answers1

1

.NET usually uses shallow copies during Clone operations.

In order to implement deep copies, you typically have 2 options

  1. Serialize / deserialize (if your classes are all serializable) - e.g. Here
  2. By using reflection e.g. Here

If you split your data (model) concerns out of your form (view), you can then more easily 'clone' just the data.

Community
  • 1
  • 1
StuartLC
  • 104,537
  • 17
  • 209
  • 285