Two 2 ways to create copy of a source object

/// <summary>

/// Makes deep copy of a source object, the source object

/// must be marked with the Serializable attribute

/// </summary>

/// <typeparam name="T">must be referenced type</typeparam>

/// <param name="source">source object</param>

/// <returns>new copy of the source object</returns>

public static T DeepCopy<T>(T source) where T: class

{

    if (source == null) throw new ArgumentNullException("source");

    BinaryFormatter formater = new BinaryFormatter();

    MemoryStream stream = new MemoryStream();

    formater.Serialize(stream, source);

    stream.Position = 0;

    return (T)formater.Deserialize(stream);

}

 

/// <summary>

/// Makes shallow copy of an input object

/// </summary>

/// <typeparam name="T">Type of the object</typeparam>

/// <param name="inputObject">object which will be copied</param>

/// <returns>returns shallow copy of the input object</returns>

public static T GetShallowCopy<T>(T inputObject)

{

    if (inputObject == null) throw new ArgumentNullException("inputObject");           

    return (T)inputObject.GetType().GetMethod("MemberwiseClone", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(inputObject, null);

}

 

By the way

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s