user1306322
user1306322

Reputation: 8721

How to automatically convert derived class object to new base class object?

B is a class derived from A. I need to create a new object A from existing object B.

I need this because in my application I use a lot of A instances which are much more light weigh than B (which holds a lot of reference data), otherwise I would run out of memory.

How do I convert B to A without manually copying all A's fields' values in a custom method?

Upvotes: 1

Views: 585

Answers (2)

slugster
slugster

Reputation: 49965

Just cast it:

var a = (A)b;

or

var a = b as A;

A class that extends another can always be cast down to the more primitive version. Note that under the hood this is still the same instance of B, you are just treating it as A. If you are looking to create a clone of B, then you should add a method to B:

public class B : A  
{
    public A Clone()
    {
        var a = new A();
        a.SomeProperty = this.SomeProperty;
        ...etc...
        return a;
    }
}

Upvotes: 0

Matthew Strawbridge
Matthew Strawbridge

Reputation: 20640

Consider using composition (i.e. your B contains a private A as member data) instead of inheritance. Add a method to B to return its A, so you can keep hold of it while the rest of the B is garbage collected.

Upvotes: 2

Related Questions