I have found one solution to this, not saying it's the best one, but it feels clean to me and doesn't require any major changes to my code. My code looked similar to yours until I realized it didn't work.
My Base Class
public class MyBaseClass
{
public string BaseProperty1 { get; set; }
public string BaseProperty2 { get; set; }
public string BaseProperty3 { get; set; }
public string BaseProperty4 { get; set; }
public string BaseProperty5 { get; set; }
}
My Derived Class
public class MyDerivedClass : MyBaseClass
{
public string DerivedProperty1 { get; set; }
public string DerivedProperty2 { get; set; }
public string DerivedProperty3 { get; set; }
}
Previous method to get a populated base class
public MyBaseClass GetPopulatedBaseClass()
{
var myBaseClass = new MyBaseClass();
myBaseClass.BaseProperty1 = "Something"
myBaseClass.BaseProperty2 = "Something else"
myBaseClass.BaseProperty3 = "Something more"
//etc...
return myBaseClass;
}
Before I was trying this, which gave me a unable to cast error
public MyDerivedClass GetPopulatedDerivedClass()
{
var newDerivedClass = (MyDerivedClass)GetPopulatedBaseClass();
newDerivedClass.UniqueProperty1 = "Some One";
newDerivedClass.UniqueProperty2 = "Some Thing";
newDerivedClass.UniqueProperty3 = "Some Thing Else";
return newDerivedClass;
}
I changed my code as follows bellow and it seems to work and makes more sense now:
Old
public MyBaseClass GetPopulatedBaseClass()
{
var myBaseClass = new MyBaseClass();
myBaseClass.BaseProperty1 = "Something"
myBaseClass.BaseProperty2 = "Something else"
myBaseClass.BaseProperty3 = "Something more"
//etc...
return myBaseClass;
}
New
public void FillBaseClass(MyBaseClass myBaseClass)
{
myBaseClass.BaseProperty1 = "Something"
myBaseClass.BaseProperty2 = "Something else"
myBaseClass.BaseProperty3 = "Something more"
//etc...
}
Old
public MyDerivedClass GetPopulatedDerivedClass()
{
var newDerivedClass = (MyDerivedClass)GetPopulatedBaseClass();
newDerivedClass.UniqueProperty1 = "Some One";
newDerivedClass.UniqueProperty2 = "Some Thing";
newDerivedClass.UniqueProperty3 = "Some Thing Else";
return newDerivedClass;
}
New
public MyDerivedClass GetPopulatedDerivedClass()
{
var newDerivedClass = new MyDerivedClass();
FillBaseClass(newDerivedClass);
newDerivedClass.UniqueProperty1 = "Some One";
newDerivedClass.UniqueProperty2 = "Some Thing";
newDerivedClass.UniqueProperty3 = "Some Thing Else";
return newDerivedClass;
}