Some time ago I wrote a post No Copy Constructor support in .Net framework.
I’ve created Copy method to copy Fields(not only properties, and found that the private fields of any base class are not copied.
The article Where are my fields? « Andrew Smith explains that it’s required to iterate base classes.
But when looking in the Google for the solution,I’ve found the suggestion for serializable objects:
object data =FormatterServices.GetObjectData(from, sm);
FormatterServices.PopulateObjectMembers(to, sm, data);
It seems to solve my requirement better than the reflection approach:
/// Inspired by http://geekswithblogs.net/thibbard/archive/2007/05/04/Architecture-thoughts-and-Reflection.aspx
publicstaticbool CopyFleldsFromBaseClass(object from,object to)
bool rv = false;
if (from == null)
thrownewApplicationException("from is null");
if (to == null)
thrownewApplicationException("to is null");
System.Type typeFrom = from.GetType();
System.Type typeTo = from.GetType();
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public ;
//Debug.Assert(typeTo is typeFrom);
//iterate through each property of this
foreach (FieldInfo prop in typeFrom.GetFields(bindingFlags))
//get the name of the current property
string memberName = prop.Name;
//make sure this property is writeable and the obj property is readable
//if (prop.CanRead && to.GetType().GetFields(memberName).CanWrite)
if (typeTo.GetField(memberName, bindingFlags) != null)
//Get the value of this current property from obj
object objValue = typeFrom.GetField(memberName, bindingFlags).GetValue(from);
//Set the value of this property from obj
//if we are here, everything worked
rv = true;
catch (Exception exc)
//something bad happened, return false
rv = false;
By the way, my original idea was to create a derived class, when I have an object of base class.
Later I understood that it's better to create the derived object using factory at the start,
rather than create the base class and then convert it to derived one.
Related link on Rick Strahl's Blog Simplistic Object Copying in .NET
Similar Reflection approach to implement ToString is described here