Created
September 10, 2013 18:24
-
-
Save gscattolin/6513442 to your computer and use it in GitHub Desktop.
Deep copy, clone, ICloneable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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