Monday, January 30, 2012

Best Extension Methods: Clone

This extension method to get a clone of an object
    /// Makes a copy from the object.
    /// Doesn't copy the reference memory, only data.
    /// Type of the return object.
    /// Object to be copied.
    /// Returns the copied object.
    public static T Clone(this object item)
        if (item != null)
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();

            formatter.Serialize(stream, item);
            stream.Seek(0, SeekOrigin.Begin);

            T result = (T)formatter.Deserialize(stream);


            return result;
            return default(T);

Compiled By: Rajesh Rolen

Share This!

No comments:

Powered By Blogger · Designed By Seo Blogger Templates