cast the Parent object to Child object in C#
I do so (this is just an example):
using System.Reflection;
public class DefaultObject
{
...
}
public class ExtendedObject : DefaultObject
{
....
public DefaultObject Parent { get; set; }
public ExtendedObject() {}
public ExtendedObject(DefaultObject parent)
{
Parent = parent;
foreach (PropertyInfo prop in parent.GetType().GetProperties())
GetType().GetProperty(prop.Name).SetValue(this, prop.GetValue(parent, null), null);
}
}
Using:
DefaultObject default = new DefaultObject { /* propery initialization */ };
ExtendedObject extended = new ExtendedObject(default); // now all properties of extended are initialized by values of default properties.
MessageBox.Show(extended.Parent.ToString()); // now you can get reference to parent object
If I understand your "I just want to fill them automatically" comment correctly, you want to create a new Child object that's populated with the values of the Parent, with default values for the new properties. Best way to do that is to create a constructor that copies the values:
public class Parent
{
public string FirstName {get; set;}
public string LastName {get; set;}
public string City {get; set;}
}
public class Child : Parent
{
public string PhoneNumber {get; set;}
public string MobileNumber {get; set;}
public Child (Parent parentToCopy)
{
this.FirstName = parentToCopy.FirstName;
this.LastName = parentToCopy.LastName;
this.City = parentToCopy.City;
this.PhoneNumber = string.Empty; // Or any other default.
this.MobileNumber = string.Empty;
}
}
Now you can use LINQ, like the answers above, to create a Child out of each Parent:
List<Child> lstChild = lstParent.Select(parent => new Child(parent)).ToList();
Note that this is very similar to @daryal's answer, but wraps the parent-to-child copying logic inside the constructor, rather than having it outside in the new Child()
call.
I did like this:
class Parent
{
...
}
class Child :Parent
{
...
public Child(Parent p)
{
foreach (FieldInfo prop in p.GetType().GetFields())
GetType().GetField(prop.Name).SetValue(this, prop.GetValue( p));
foreach (PropertyInfo prop in p.GetType().GetProperties())
GetType().GetProperty(prop.Name).SetValue(this, prop.GetValue( p, null), null);
}
}