Reputation: 2363
I am encounter with a situation where I need to copy the members of base class to derived class. I have an Instance of Base class which are returning by some other service, the same class we have used as a base class for further classes.
When we crates an object of derived class I want to assign the already created instance of base class to derived class, I know we can not assign the base class object to derived class but I am still searching any other solution. Any one has any Idea?
Example :
public class VBase
{
public string Type {get;set;}
public string Colour {get;set;}
}
public class Car : VBase
{
public string Name {get;set;}
public int Year {get;set;}
}
// This class instance I am getting from some other source
VBase mBase= new VBase();
mBase.Type = "SUV";
mBase.Colour = "Black";
//-------------------------------------------------------
Car myCar= new Car();
myCar.Name = "AUDI";
mBase.Year = "2016";
//here I want to copy the instance of base class to derived class some thing like this or any other possible way.
myCar.base=mBase;
Upvotes: 4
Views: 83
Reputation: 3500
Without using reflection, if your classes are lightweight, and wont change overtime, then you could create a public property of Base in Car
:
public class Car : VBase
{
public string Name
{
get;
set;
}
public int Year
{
get;
set;
}
public VBase Base
{
set
{
base.Type = value.Type;
base.Colour = value.Colour;
}
}
}
You can then easily pass through your base class like so:
myCar.Base = mBase;
I have created a dotnetfiddle here:
dotnetfiddle for this question
Upvotes: 0
Reputation: 25080
It is not possible in naïve way.
I'd like to recommend to define constructor or static method. I personally do not recommend to use additional libraries like AutoMapper for this job as they could require some conversion and make code cumbersome.
public class Car : VBase
{
// Method 1: define constructor.
public class Car(VBase v) {
this.Type = v.Type;
this.Colour = v.Colour;
}
// Method 2: static method.
public static Car FromVBase(VBase v){
return new Car()
{
this.Type = v.Type;
this.Colour = v.Colour;
};
}
public string Name {get;set;}
public int Year {get;set;}
}
Upvotes: 2