Intelligent Copy Constructor

14 Apr

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



One response to “Intelligent Copy Constructor

  1. hmm...?

    October 13, 2010 at 07:35



Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: