Is there a way to transform a base class into its derived class?
Here is a simple example of two classes:
namespace BLL
{
public class Contact
{
public int ContactID { get; set; }
public string Name { get; set; }
public Contact(){}
}
}
namespace BLL
{
public class SpecialContact : Contact
{
public SpecialContact(){}
}
}
Ideally, I could do something like this:
Contact contact = new Contact();
SpecialContact specialContact = new SpecialContact();
contact.ContactID = 123;
contact.Name = "Jeff";
specialContact = contact;
This code of course throws an error. Apart from writing another constructor for SpecialContact or method that sets each property, is there any other solution?
It is illegal to assign
Baseclass reference to theDerivedclass reference variable.Variable of type
Xcan only be a reference to an object of typeXor derived.You probably need to have another instance of
SpecialContactwhich contains the same data as existing object. There is no way to avoid manual copying.I use the following extension method when I need to copy the matching properties from one object to another incompatible one(1):
Then you can do:
Please consider this a workaround. The proper solution would be to design properly your class hierarchy where you do not come to this problem.
1 Note: it matches the properties by name and assumes they are of the same type.