I have two classes which should be exactly the same apart from 1 class needed another property.
Instead of re-writing all of the properties twice, I thought of inheriting all of the properties from BaseClass with just the one extra property in MyNewClass
public class BaseClass
{
public int BaseProperty1 { get; set; }
public int BaseProperty2 { get; set; }
public int BaseProperty3 { get; set; }
}
public class MyNewClass: BaseClass
{
public int? ExtraProperty{ get; set; }
}
Since I already fill in all of the details for the original BaseClass in my function, It would be far easier to be able to use this instance of the class to fill in the details of the new instance of MyNewClass.
I hoped it would be as simple as the following, but unfortunately I get the error: System.InvalidCastException: 'Unable to cast object of type 'BaseClass' to type 'MyNewClass'.'
MyNewClass myNewClass= new MyNewClass();
myNewClass = (MyNewClass)baseClass; //baseClass is alread populated at this point
myNewClass.ExtraProperty = 1;
Is there any way to quickly populate a class using another class which has one less property?
I could just set each property individually, but the class which I am using is quite large and it feels like bad practice.
Thanks in advance for any help.