Background
I am trying to create a copy of a business object I have created in VB.NET. I have implemented the ICloneable interface and in the Clone function, I create a copy of the object by serializing it with a BinaryFormatter and then de-serializing straight back out into another object which I return from the function.
The class I am trying to serialize is marked as "Serializable" along with the child objects that are contained within the class.
I have tested that the clone method works by writing code similar to the following:
Dim obj as New Sheep()
Dim dolly as Sheep = obj.Clone()
All works fine at this point.
Problem
I have a custom windows forms control which inherits from a 3rd party control. This custom control basically contains the object which I want to clone (as this object ultimatly feeds the 3rd party control).
I want to create a clone of the object within the windows form control so that I can allow the user to manipulate the properties whilst having the option of cancelling the changes and reverting the object back to how it was before they made the changes. I would like to take the copy of the object before the user starts making changes and hold onto it so I have it ready if they press cancel.
My thought would be to write code along the lines of the following:
Dim copy as Sheep = MyControl.Sheep.Clone()
Then allow the user to manipulate the properties on MyControl.Sheep
. When I attempt to do this however, the clone method throws an exception stating:
*Type 'MyControl' in Assembly 'My_Assembly_Info_Here' is not marked as serializable*
This error is thrown at the point where I call BinaryFormatter.Serialize(stream,Me)
.
I have tried creating a method on MyControl
that returns a copy of the object and also first assigning MyControl.Sheep
to another variable and then cloning the variable but nothing seems to work. However, creating a new instance of the object directly and cloning it works fine!
Any idea's where I am going wrong?
Solution
Marc's answer helped point me in the right direction on this one. This blog post from Rocky Lhotka explains the problem and how to solve it.