Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone an Object that I can't add ICloneable to

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!

like image 909
MattW Avatar asked Aug 30 '11 18:08

MattW


People also ask

Which of the following method should be implemented when ICloneable interface is used?

ICloneable interface) should contain public or protected copy constructor. Base class should declare Clone method as virtual. Derived class should contain copy constructor which calls base class's copy constructor. Both base and derived class should implement Clone method by simply invoking the copy constructor.

What is ICloneable interface in C#?

The ICloneable interface enables you to provide a customized implementation that creates a copy of an existing object. The ICloneable interface contains one member, the Clone method, which is intended to provide cloning support beyond that supplied by Object.

What is difference between copy and clone in C#?

clone - create something new based on something that exists. copying - copy from something that exists to something else (that also already exists).


1 Answers

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));
like image 128
Sign Avatar answered Sep 30 '22 07:09

Sign