Wednesday, November 09, 2005

Copy constructor for child object

Many times we faced the situation where we want to do something like this:

A a=new B();

Where A is the child object and B is the parent which is not possible. We can achieve this goal by copy constructor like this:

public BaseEntity(ref object parent):this()
{
if(parent==null)
return;
FieldInfo [] fields;
if(parent.GetType()==this.GetType().BaseType)
fields=parent.GetType().GetFields(BindingFlags.Instance BindingFlags.Public BindingFlags.NonPublic);
else
fields=this.GetType().GetFields(BindingFlags.Instance BindingFlags.Public BindingFlags.NonPublic);
foreach(FieldInfo field in fields)
{
object val=field.GetValue(parent);
field.SetValue(this, val);
}
}

It works like:

B b=new B();
A a=new A(b);

No comments: