Cloning Objects in C#

After trying to manually clone some classes, but making a sort of copy constructor I was always ending up with lot’s of code and worse, if I add another variable to my class I would sometimes forgot to also clone it. Luckily and after a search I discovered that C# has a cool thing, Reflection. So you can do something like this:

using System.Reflection;
class MyClass {
 public int a;
 public float x;
 // default constructor
MyClass (MyClass my)
   FieldInfo[] fields = typeof(MyClass).GetFields(BindingFlags.Public
   | BindingFlags.NonPublic | BindingFlags.Instance);
    foreach(FieldInfo f in fields) 
MyClass obj1 = new MyClass();
obj1.a = 1;
obj1.x = 2.0f;
MyClass obj2 = new MyClass(obj1);
 // Obj2 will have same values as obj1 and you 
// can now use them independently.

I hope this is helpful. Let me know if you know a better way

One Comment

  1. Anathol

    Reflection is a cool thing espacally in dynamic programming, but be careful… it’s executed in runtime and is really slow compared to manual copy-methods.

    Using generic Classes would do the tric at compiletime, but I never saw a really good implementation.

    A little bit faster is memmory-streaming and de/-serialization (get a look: ), but also not at fast as hardcoded copy.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.