September 2, 2004

Create a new object in the base class with the correct derived class

Sometimes you want a base class that implements an “Clone” method. No you only want to write an Copy-Constructor for each derived class, you do NOT want to write an new virtual/override Clone method.

The easiest way to archive this is the following:

 using System;
 namespace Test
 {
   class Class1
   {
     static void Main(string[] args)
     {
       A a = new A();
       A a1 = a.Clone(); // we created a A-instance!

       B b = new B();
       A b1 = b.Clone(); // we created a B-instance!

       C c = new C();
       A c1 = c.Clone(); // we created a C-instance!

       D d = new D();
       A d1 = d.Clone(); // we created a D-instance!
     }
   }

  class A
  {
    public A() {}
    public A(A val) {}  // copy constructor
    public A Clone()
    {
      System.Type t = this.GetType();
      object [] args = new object[ 1 ] {this};
      object newobj = System.Activator.CreateInstance(t, args);
      return (A) newobj;
    }
  }
  class B : A
  {
    public B() {}
    public B(B val) : base(val) {}  // copy constructor
  }
  class C : A
  {
    public C() {}
    public C(C val) : base(val) {}  // copy constructor
  }
  class D : C
  {
    public D() {}
    public D(D val) : base(val) {}  // copy constructor
  }
}

Posted 3 years, 5 months ago on September 2, 2004
The trackback url for this post is http://blog.kalmbachnet.de/bblog/trackback.php/10/

Comments have now been turned off for this post