Post Format

An Intelligent Copy Constructor In C# Using Reflection

6 comments

Whenever I write a copy constructor I know that at some point I'm going to add a field to the class, forget to add it to the copy constructor and cause a difficult-to-identify bug later on down the line. So I came up with a simple solution in C# to this problem using Reflection. Here's the code (oh, you'll need to put 'Using System.Reflection;' at the top of the file):

    public MyClass( MyClass rhs )
    {
        // get all the fields in the class
        FieldInfo[] fields_of_class = this.GetType().GetFields(
          BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance );

        // copy each value over to 'this'
        foreach( FieldInfo fi in fields_of_class )
        {
            fi.SetValue( this, fi.GetValue( rhs ) );
        }
    }

Basically, it enumerates all the public and non-public fields in the class and copies their values from the class passed in. You can modify the flags passed to GetFields() to include or exclude fields as you need. So now I can't miss out any fields that I add to the class – and that means at least one less bug I've caused!

Clarification: This sample only performs a shallow copy of MyClass and therefore if you have fields that are reference types (like classes), then it will only copy a reference to those fields from 'rhs'. The class I used this for only contained value types (like int's and so forth) and so works exactly as I'd expect. I'll leave the modifications to this code to handle reference types as an exercise for the reader!

Posted by

Creator of John's Background Switcher. Scotsman, footballer, photographer, dog owner, risk taker, heart breaker, nice guy. Some of those are lies.

6 Comments Join the Conversation

  1. This is only performing a reference copy, so the new object is pointing to the same object as the source.

    Reply

  2. What you of course mean is that this works only for value types (like int, double and string) within MyClass and not reference types – which is quite correct. But I don’t care – the class I wrote it for only contained value types! You don’t expect me to do all your work for you do you?! 😉

    Reply

Leave a Reply

Required fields are marked *.

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com 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