Dave Hanna
Dave Hanna

Reputation: 2521

Creating an instance of a derived class from an instance of the parent class

In general, given a class A, and a derived class DerivedFromA, and an instance of A, is there a way to construct DerivedFromA from that instance?

E.g., let's say that DerivedFromA simply overrides one or more methods or properties of A. Let's say I have some Container class with a CreateA() method that returns an instance of A, and I either can't or don't want to override or otherwise mess with that Container class. What I want to do is take the instance returned by Container.CreateA(), pass it to a DerivedFromA( A instanceOfA) constructor and have the resulting object be treated just like instanceOfA and use all of instanceOfA's methods, properties, and data except for the ones I have overridden.

BTW, the language in question is C#, it that makes a difference.

Thanks.

Upvotes: 2

Views: 1814

Answers (2)

CodeNaked
CodeNaked

Reputation: 41393

I would probably make this a new virtual method like so:

public class ClassA {
    public virtual string Foo { get; set };

    public virtual ClassA GetAsClassA() {
        return this;
    }
}


public class ClassB : ClassA {
    public virtual string Foo { get; set };

    public override ClassA GetAsClassA() {
        // Create new ClassA and copy properties as needed.
        // Can use base.Foo to get base properties, as needed.
    }
}

This wraps up the logic into the classes themselves.

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564333

You'll have to make a new DerivedFromA instance, and use that instance instead of your original. If you do that, however, it will work fine.

Just add a constructor like you showed:

public DerivedFromA(A instanceOfA)
{
    // Copy members from instanceOfA into here as necessary
    this.Foo = instanceOfA.Foo;
    this.Bar = instanceOfA.Bar;

    // Setup unique values
    this.Baz = 42;
}

Then, when you call, you can just do:

DerivedFromA instance = new DerivedFromA(container.CreateA());

Upvotes: 2

Related Questions