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; MyClass() { // default constructor } MyClass (MyClass my) { FieldInfo[] fields = typeof(MyClass).GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); foreach(FieldInfo f in fields) { f.SetValue(this,f.GetValue(oth)); } } } 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 ...

October 12, 2009 · 1 min · 146 words · David Amador