How to initialize inherited class with base class?
You can create a constructor in your derived class and map the objects,
public class MyInheritedClass : MyClass
{
MyInheritedClass (MyClass baseObject)
{
this.UserName = baseObject.UserName; // Do it similarly for rest of the properties
}
public string Email { get; set; }
}
MyInheritedClass inheritedClassObject = new MyInheritedClass(myClassObject);
inheritedClassObject.GetJson();
Updated Constructor :
MyInheritedClass (MyClass baseObject)
{
//Get the list of properties available in base class
var properties = baseObject.GetProperties();
properties.ToList().ForEach(property =>
{
//Check whether that property is present in derived class
var isPresent = this.GetType().GetProperty(property);
if (isPresent != null && property.CanWrite)
{
//If present get the value and map it
var value = baseObject.GetType().GetProperty(property).GetValue(baseObject, null);
this.GetType().GetProperty(property).SetValue(this, value, null);
}
});
}
One of the options is to serialize the base class object and then deserialize it to derived class.
E.g. you can use Json.Net serializer
var jsonSerializerSettings = new JsonSerializerSettings
{ //You can specify other settings or no settings at all
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
string jsonFromBase = JsonConvert.SerializeObject(baseObject, Formatting.Indented, jsonSerializerSettings);
derivedClass= JsonConvert.DeserializeObject<DerivedClass>(jsonFromBase) ;
You just need to create an instance of child class that is MyInheritedClass
and it will hold all the properties from both the classes.
When you create an instance of child class MyInheritedClass
, runtime will call the constructor of Parent class MyInheritedClass
first to allocate the memory for the member of parent class and then child class constructor will be invoked.
So instance of Child class will have all the properties and you are referring to the this
while serializing the object so it should have all the properties serialized in json.
Note: Even though you are serializing the object inside the method that is declared in parent class, referring to this
object will refer to the current instance that is instance of Child class so will hold all the properties.