Created
November 19, 2013 08:27
-
-
Save thakurarun/7542106 to your computer and use it in GitHub Desktop.
Sample for making deep copy of any object in c#
This file contains 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
[Serializable] | |
public class temp | |
{ | |
public int a; | |
} | |
class Program | |
{ | |
public static T DeepClone<T>(T a) | |
{ | |
using (MemoryStream stream = new MemoryStream()) | |
{ | |
BinaryFormatter formatter = new BinaryFormatter(); | |
formatter.Serialize(stream, a); | |
stream.Position = 0; | |
return (T)formatter.Deserialize(stream); | |
} | |
} | |
static void Main(string[] args) | |
{ | |
List<temp> list1 = new List<temp>(); | |
list1.Add(new temp { a = 1 }); | |
list1.Add(new temp { a = 2 }); | |
list1.Add(new temp { a = 3 }); | |
List<temp> list2 = DeepClone<List<temp>>(list1); | |
list1[1].a = 4; | |
Console.WriteLine(list2[1].a); | |
Console.ReadKey(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment