How to make a new object by its base class?

  • Thread starter Thread starter johan Goris
  • Start date Start date
J

johan Goris

ObjectR is an ObjectA
ObjectS is an ObjectA
....

public ObjectA Copy(ObjectA oa)
{
return ..... // new ObjectR when oa is an ObjectR ..
// new ObjectS when oa is an ObjectS....
}

The code should be in such way that the method will work even when new
classes (derived from class ObjectA) is made. And without altering the code
in Method Copy from ObjectA.
 
abstract class ObjectA
{
public abstract ObjectA Clone ( );
}

class ObjectR
: ObjectA
{
public override ObjectA Clone ( )
{
ObjectR r = new ObjectR();
r.Whatever = _whatever;
r.AnotherProperty = _anotherProperty;
return r;
}
}
 
public ObjectA Copy(ObjectA oa)
{
return ..... // new ObjectR when oa is an ObjectR ..
// new ObjectS when oa is an ObjectS....
}

The code should be in such way that the method will work even when new
classes (derived from class ObjectA) is made. And without altering the
code in Method Copy from ObjectA.

For this you need at least an copy constructor for each class!

But the solution is simple:

public A Clone()
{
System.Type t = this.GetType();
object [] args = new object1 {this};
object newobj = System.Activator.CreateInstance(t, args);
return (A) newobj;
}


See: Create a new object in the base class with the correct derived class
http://blog.kalmbachnet.de/?postid=10

--
Greetings
Jochen

My blog about Win32 and .NET
http://blog.kalmbachnet.de/
 
Hi,


You have two options depending if you can change the code of ObjectA,R,S

if you can, then create a n abstract method in A that the derived classes
will override and return the correct type. You can select if you will clone
it or just create a new one, either by using two methods or passing a
parameter.

If you do not have access to change the code then you must check the type of
the object using the is operator and then create the new instance with this
info.

cheers,
 
Back
Top