Hi i want to cast the Parent object to Child object in C#
public class Parent
{
public string FirstName {get; set;}
public string LastName {get; set;
Another way to approach this solution is to have the Parent
control the copy logic and Child
will pass the copy source into the base
constructor.
e.g. iterating on Avner's solution
public class Parent
{
public string FirstName {get; set;}
public string LastName {get; set;}
public string City {get; set;}
public Parent()
{
}
public Parent(Parent copyFrom)
{
this.FirstName = copyFrom.FirstName;
this.LastName = copyFrom.LastName;
this.City = copyFrom.City;
}
}
public class Child : Parent
{
public string PhoneNumber {get; set;}
public string MobileNumber {get; set;}
public Child (Parent parentToCopy) : base(parentToCopy)
{
}
}
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);
}
}
var lstChild = lstParent.Cast<Child>().ToList();
or
var lstChild = lstParent.ConvertAll(x=>(Child)x);
Both of these, however, assume that the Parent
list actually contains Child
instances. You can't change the actual type of an object.
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
You may use reflection as well, but this is simpler for your case.
foreach(var obj in lstParent)
{
Child child = new Child(){ FirstName = obj.FirstName, LastName=obj.LastName, City = obj.City};
child.MobileNumber = "some mobile number";
child.PhoneNumber = "some phone number";
lstChild.Add((Child)obj);
}
This is what I came up with form my solution.
public static void ShallowConvert<T, U>(this T parent, U child)
{
foreach (PropertyInfo property in parent.GetType().GetProperties())
{
if (property.CanWrite)
{
property.SetValue(child, property.GetValue(parent, null), null);
}
}
}