7

I am trying to create a shallow copy (new instance) of an object, without manually setting each field. This object is not a type I have the ability to modify, so I cannot go into the object and implement ICloneable ... I am a bit stuck. Is there an easy way to simply clone an object, or will I have to implement some Clone() method that simply copies each field into a new object?

Thanks in advance for any help!

MattW
  • 12,902
  • 5
  • 38
  • 65
  • Take a look at AutoMapper @ http://automapper.codeplex.com/ – Chandu Aug 30 '11 at 18:47
  • will object.MemberwiseClone work? http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx – cadrell0 Aug 30 '11 at 19:40
  • If I was able to edit the object (class file) I wanted to clone then yes, however this object is from a 3rd party DLL, and I don't have the access to add the ability to call MemberwiseClone() ... unless I am missing something. – MattW Aug 30 '11 at 19:53

1 Answers1

7

Use reflection to look at the fields on the object and use that to populate the new instance.

This makes some assumptions about the existence of a constructor that takes no arguments.

Type t = typeof(typeToClone);
var fields = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
var copy = Activator.CreateInstance(t);
for(int i = 0; i < fields.Length; i++)
  fields[i].SetValue(copy, fields[i].GetValue(existing));
Sign
  • 1,919
  • 18
  • 33