Saturday, September 03, 2005

clone object in dotnet

private static void TestClone()
{
Person p1 = new Person();
p1.Age = 26;
p1.UserName = "yyanghhong";

Person p2 = (Person)CloneObjectEx(p1);
p2.UserName = "unruledboy";

Console.WriteLine(p1.UserName);
Console.WriteLine(p2.UserName);
}

public static Person CloneObject(Person ObjectInstance)
{
BinaryFormatter bFormatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
bFormatter.Serialize(stream, ObjectInstance);
stream.Seek(0, SeekOrigin.Begin);
Person newObject = (Person)bFormatter.Deserialize(stream);
return newObject;
}

public static object CloneObjectEx(object ObjectInstance)
{
BinaryFormatter bFormatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
bFormatter.Serialize(stream, ObjectInstance);
stream.Seek(0, SeekOrigin.Begin);
return bFormatter.Deserialize(stream);
}

[Serializable]
public class Person
{
private int age;
private string userName;

public Person()
{
}

public int Age
{
get{return age;}
set{age = value;}
}
public string UserName
{
get{return userName;}
set{userName = value;}
}
}

Google Code

Google Code