Tag Archives: Copy Constructor

Intelligent Copy Constructor

Whenever I wanted to add a new field to a class that has a copy constructor I had to add the new field into the body of the copy constructor.
Fact that this is very dangerous, I thought I implement a copy constructor that works with reflections.
This piece of code enumerates all fields of MyClass and copies the values in the new created object.

public MyClass(MyClass mc)
    FieldInfo[] classfields= GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
    foreach (FieldInfo fi in classfields)
        fi.SetValue(this, fi.GetValue(mc));
1 Comment

Posted by on April 14, 2010 in C-Sharp