Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform class to a derived class

Tags:

c#

inheritance

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?

like image 716
Josh Avatar asked Aug 08 '26 11:08

Josh


1 Answers

It is illegal to assign Base class reference to the Derived class reference variable.

Variable of type X can only be a reference to an object of type X or derived.

You probably need to have another instance of SpecialContact which 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):

public static void AssignFrom(this object destination, object source) {
  Type dest_type = destination.GetType();
  Type source_type = source.GetType();

  var matching_props = from d in dest_type.GetProperties()
                        join s in source_type.GetProperties()
                        on d.Name equals s.Name
                        where d.IsWritable() && s.IsReadable()
                        select new {
                          source = s,
                          destination = d
                        };

  foreach (var prop in matching_props) {
    prop.destination.SetValue(destination, prop.source.GetValue(source, null), null);
  }
}

Then you can do:

specialContact.assignFrom(contact);

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.

like image 183
Krizz Avatar answered Aug 11 '26 01:08

Krizz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!