Search code examples
c#classboxingunboxing

Box object and intendedly lose unnecessary/extra data?


How can I box an object (e.g. from type B to type A) and intendedly lose the extra data?

Example:

class A
{
    private string a;
    private DateTime time;

    public A(string a)
    {
        this.a = a;
        this.time = DateTime.Now;
    }
}

//...

class B:A
{
    private string b;

    public B(string a, string b):base(a)
    {
        this.b = b;
    }
}

//...

B b1 = new B("A", "B");

A a1 = (A)b; // Still has variable b

In this example I created a B and then boxed it into an A. The new A has still the b variable saved in it, because in reality it points to the B object.

I know I could create a new A with the old data from B, but (in this example) if I call the constructor of A with the old data of B, the time variable would be wrong.


Solution

  • You can't. You cannot change the type of an object in .NET. When it has been created, the type is fixed. That B object is a B when you made it, it's a B now, and it will continue to be a B until it gets collected.

    If you want an A, you need to make an A.