Emil’s Blog

Programming Windows, .Net, EPiServer and whatnot…

[Powered by WordPress.]

December 13, 2005

Cloning an object using serialization

by @ 15:04. Filed under .Net programming

Here's an easy way of cloning an object (deep copy):

public T CloneObject<T>(T obj) where T:class
{
    if (obj== null)
        return null;

    MemoryStream memstream = new MemoryStream();
    IFormatter formatter = new BinaryFormatter();
    formatter.Serialize(memstream, obj);
    memstream.Seek(0, SeekOrigin.Begin);
    T clone = (T)formatter.Deserialize(memstream);
    memstream.Close();
    return clone;
}

The requirement is of course that the object is serializable and marked with the [Serializable] attribute.

[powered by WordPress.]

jour·nal n. A personal record of occurrences, experiences, and reflections kept on a regular basis; a diary.

Internal links:

Categories:

Search blog:

Archives:

December 2005
M T W T F S S
« Oct   Jan »
 1234
567891011
12131415161718
19202122232425
262728293031  


View Emil Åström's profile on LinkedIn

General links:

I read:

Visitors

Recent Comments

Spam caught

Other:

Clicky Web Analytics

36 queries. 0.352 seconds