Reputation: 19956
I have a class, for example:
class BaseDataPoint
{
public double A;
public double B;
}
and later on in the code, I need to extend that to
class ReportDataPoint : BaseDataPoint
{
public double C;
}
Since above is only an example, and there are lot more fields to copy, is it possible (via some trick) to 'convert' BaseDataPoint
instance to ReportDataPoint
without manually copying field by field?
If I have
BaseDataPoint p1;
...
ReportDataPoint p2=(ReportDataPoint)p1; // FAILS at runtime
ReportDataPoint p3=new ReportDataPoint(p1); // can't compile
Upvotes: 2
Views: 147
Reputation: 345
It only depends on the type of the instance you create.
If you try :
BaseDataPoint p1 = new ReportDataPoint();
You will be able to cast it later.
otherwise you can implement a generic util class to transfer field values between instance types. once for all.
Upvotes: 0
Reputation: 2439
Just write a constructor inside ReportDataPoint, so that p3's initialisation will compile. It's work, but it'll enable you to define default values for the newer fields. class
BaseDataPoint
{
public double A;
public double B;
public BaseDataPoint(double A, double B)
{
this.A = A;
this.B = B;
}
}
class ReportDataPoint : BaseDataPoint
{
static const double defaultCValue = 0.0;
public double C;
public ReportDataPoint(double A, double B, double C)
:base(A,B){
this.C = C;
}
public ReportDataPoint(BaseDataPoint p,double C=defaultCValue) :
this(p.A, p.B, C)
{ }
}
...
BaseDataPoint p1=new BaseDataPoint(1,2);
ReportDataPoint p2=new ReportDataPoint(p1);
Upvotes: 1
Reputation: 1062865
You can't change the type of an instance; you need to create a new instance. Furthermore, you can't use the cast syntax for this since you re not allowed to add custom operators within the inheritance chain.
So; either add a manual conversion (via adding a constructor like your example, or a ComvertTo method) - or there are a few libraries that may help (maybe AutoMapper, up it some serialization lins might help too).
Upvotes: 1
Reputation: 14784
Not that I know of. In cases like this I would just implement a constructor for ReportDataPoint that accepts a BaseDataPoint instance and copies the relevant data.
Upvotes: 0