Copy objects

  • Thread starter Thread starter pnp
  • Start date Start date
P

pnp

I have two objects AA and AB that derive from object A. These two
objects have common atts that they inherit from object A but also some
of their own.

I have a pointer to an AA object and i would like to turn it to a
pointer to an AB object, but maintaining the common information of these
objects, such as the atts for example.

How can I do this?
 
In the simple form, you can't. If you have a reference to an Apple, you can
change that to a reference to a Pear, even though, as types, they are both
fruit. The further question is why you'd want to do this? Some insight to
your situation could provide us with a clearer understanding of what you're
trying to do.

That said, you could write up a parent copy method that copies the data
member values. This could then be called by a child instance. It's not what
you've asked for, because you'd end up having two obects. AB could be a new
"uninitialized" object that calls this method, passing in the reference to
an instance of an AA object. The method simple knows what data members it
can retrieve values from.
 
Maybe explicit cast operator overloading may help you?

Object AA will implement the cast to AB, and vice versa.
 
Actually, I have 2 usercontrol objects that derive from the same
usercontrol parent, and what I want to do is change them at runtime from
one type to another depending on what I need to display. e.g. one
holds date values while the other color values...
 
Could you please provide an example for this?

Vadym said:
Maybe explicit cast operator overloading may help you?

Object AA will implement the cast to AB, and vice versa.
 
using System;
struct Digit
{
byte value;
public Digit(byte value)
{
if (value>9) throw new ArgumentException();
this.value = value;
}

// define explicit byte-to-Digit conversion operator:
public static explicit operator Digit(byte b)
{
Digit d = new Digit(b);
Console.WriteLine("conversion occurred");
return d;
}
}

class Test
{
public static void Main()
{
try
{
byte b = 3;
Digit d = (Digit)b; // explicit conversion
}

catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
}
}
 
Back
Top