MSDN gives this example of a deep copy (http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx)
public class Person
{
public int Age;
Alternatively, if you are able to set Serializable
attribute to all involved classes, you can use serialization. For the purpose of a generic deep copy I have this object
extension method:
public static class ObjectExtensions
{
#region Methods
public static T Copy(this T source)
{
var isNotSerializable = !typeof(T).IsSerializable;
if (isNotSerializable)
throw new ArgumentException("The type must be serializable.", "source");
var sourceIsNull = ReferenceEquals(source, null);
if (sourceIsNull)
return default(T);
var formatter = new BinaryFormatter();
using (var stream = new MemoryStream())
{
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(stream);
}
}
#endregion
}
This should also copy your IdInfo
field.
Usage is simple:
var copy = obj.Copy();