I have two classes, one which inherits the other, for example:-
public class A
{
public string AA { get; set; }
public double AB { get; set; }
}
and
public class B : A
{
public double? BA { get; set; }
}
Now, I know that if I have an instance of object B, I can cast that as type A, but I have an instance of A that I want to instantiate as a type B object. I know I could put a constructor in B’s class which copies all the property values over, but the base class, A, has quite a few properties and may well have more added, so I’m worried about missing one or forgetting to add it in to B’s constructor when I add it to A. Is there an easy way of doing this, please?
——-Edit——
Thanks folks, not my use-case unfortunately, it’s a question a mate’s fired at me. As far as I’m aware there are issues and he can’t change the base class. As I understand it, the base class is one that hooks into a database call, he then wants to grab that data and add some extra properties for an admin editing screen which his code will then use to update the base data object’s properties. My first reaction was to have the base object as a property of his object, but there’s a reason it’s significantly easier for him to have it “flattened” with the tools he’s using. I didn’t think there was a way of doing this, but I thought I’d check in case I was missing something – I thought it would be easier to just ask the basic question, rather than include the background, which would probably just raise more questions and muddy the water (AFAIK he’s suffering from “circumstances beyond his control”, with this).
Typically, this is a sign of a design flaw. I would rethink your design first, and determine whether this is truly necessary, or if there is another approach you can use here. That being said…
There is no easy way to do this. If you need a
Binstance to be created from yourAinstance, you’ll really need to copy the values over to the new instance.A better option, however, would potentially be to add a (potentially
protected) constructor toAthat sets all of these properties, given anotherAinstance.Bcould then use this to create itself, which at least keeps the requirements for matching all of the properties within the class that defines them. This should make it easier to maintain this over time.