Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - How to copy/create an object as a decendent

This is easier to explain with an example. Given these two classes:

public class MyClassA
{
    public String Property_A { get; set; }
    public String Property_B { get; set; }
    public String Property_C { get; set; }
    public String Property_D { get; set; }
    ...
    public String Property_Y { get; set; }
}

public class MyClassB: MyClassA
{
    public String Property_Z { get; set; }
}

Suppose I have fully created instance of MyClassA (with all properties from A - Y filled in). Then I need to make an instance of MyClassB which is exactly the same as my instance of MyClassA but with Property_Z filled in (with a custom value of course). How can I do this?

Doing this does not work (throws and Invalid Cast Exception):

MyClassB myInstanceB = (myClassB) myInstanceA;
myInstance.Property_Z = myCustomValue;

I have not needed to do anything like this since my C++ days and I am stumped.

Any ideas?


UPDATE: I found a solution to my problem in how I create the instances. It is below. I did not mark it as the answer because it did not exactly fit my question.

like image 820
Vaccano Avatar asked Dec 17 '22 02:12

Vaccano


1 Answers

The instance you've created is a MyClassA. That is its runtime type, not MyClassB. You cannot cast a MyClassA instance to a MyClassB at runtime because MyClassB is a more specific type than MyClassA.

You need to create a brand-new instance of MyClassB. One way to clean this up is to create a constructor that takes a MyClassA, e.g.

public class MyClassB : MyClassA
{
    public MyClassB(MyClassA a, string z)
    {
        this.PropertyA = a.PropertyA;
        this.PropertyB = a.PropertyB;
        // etc.
        this.PropertyZ = z;
    }

    public string PropertyZ { get; set; }
}
like image 157
Aaronaught Avatar answered Jan 02 '23 20:01

Aaronaught