So I'm reading my C# book and it has an example of how to create a method for creating a deep copy of an object:
[Serializable]
public class DeepClone : IDeepCopy<DeepClone>
{
public int data = 1;
public List<string> ListData = new List<string>();
public object objData = new Object();
public DeepClone DeepCopy ()
{
BinaryFormatter BF = new BinaryFormatter();
MemoryStream memSfream = new MemoryStream();
BF.Serialize(memStream,this);
memStream.Flush();
memStream.Position = 0;
return (DeepClone)BF.Deserialize(memStream);
}
}
But the method DeepCopy
is general enough that it doesn't depend on the other members
public int data = 1;
public List<string> ListData = new List<string>();
public object objData = new Object();
of the object. As far as I can tell, this method could be put in any class
and would work just the same. Additionally, how to copy an object is a question that many C# programmers have when they first use the language, as evidenced by the popularity of this thread.
This brings up the question I have about why System.Object
wasn't given a clone function. I bet programmers more often need a Clone
method than a GetHashcode
method, after all.