Skip to content

Instantly share code, notes, and snippets.

@gscattolin
Created September 10, 2013 18:24
Show Gist options
  • Select an option

  • Save gscattolin/6513442 to your computer and use it in GitHub Desktop.

Select an option

Save gscattolin/6513442 to your computer and use it in GitHub Desktop.
Deep copy, clone, ICloneable
// Shows how to return a deep copy clone of an object.
class CloneTest : ICloneable
{
public int SomeProperty { get; set; }
public object Clone()
{
CloneTest clone = new CloneTest();
clone.SomeProperty = this.SomeProperty;
return clone;
// If we only have properties to clone then we
// could simplify by returning a "shallow" copy:
//return this.MemberwiseClone();
}
public void TryThisExample()
{
// Clone an object
CloneTest original = new CloneTest();
original.SomeProperty = 123;
CloneTest clone = (CloneTest)original.Clone();
// Now both will have the same state:
Console.Write(original.SomeProperty);
Console.Write(clone.SomeProperty);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment