I have my abstract base class A:
public abstract class A : ICloneable {
public int Min { get; protected set; }
public int Max { get; protected set; }
public A(int low, int high)
{
this.Min = low;
this.Max = high;
}
//...
public object Clone()
{
return new this(this.Min, this.Max); //<-- ??
}
}
Which is extended by my class B:
public class B : A
{
public B(int low, int high) : base(low, high) { }
//...
}
Since A is abstract, it cannot be instantiated, but the derived class can. Is it possible to, from class A, create a new instance of class B?
Suppose class A has many derived classes, how will it know which one to instantiate?
Well, I want to instantiate the same class (or type) my currently A is.
That is, if I'm calling the Clone
method from a class B, I want to instantiate a new B.
If I'm calling the Clone
method from a class C, I want to instantiate a new C.
My approach was to write something like:
return new this(this.Min, this.Max);
But that doesn't seem to work nor compile.
Is it possible to accomplish this in C#?
If it isn't, is there an explanation so I can understand?
Yes, this is possible with an abstract factory method on your base class
public abstract class A
{
public int Min { get; protected set; }
public int Max { get; protected set; }
public A(int low, int high)
{
this.Min = low;
this.Max = high;
}
protected abstract A CreateInstance(int low, int high);
public object Clone()
{
return this.CreateInstance(this.Min,this.Max);
}
}
public class B:A
{
public B(int low, int high)
: base(low,high)
{
}
protected override A CreateInstance(int low, int high)
{
return new B(low,high);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With