An Intelligent Copy Constructor In C# Using Reflection
July 3rd, 2006 @ 1:40 pm | Filed under Technical
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!