It is not possible to simply drop one object of another type, even if it has one parent, because it may have different interfaces.
You need to implement an explicit or implicit ChildA (or ChildB) statement.
class ClassA { public string Property1 { get; set; } } class ClassB { public string Property2 { get; set; } public static implicit operator ClassB(ClassA classA) { return new ClassB() { Property2 = classA.Property1 }; } }
or
class ClassA { { public string Property1 { get; set; } public static explicit operator ClassB(ClassA classA) { return new ClassB() { Property2 = classA.Property1 }; } } class ClassB { public string Property2 { get; set; } }
And after implementing the negotiation operators, the following code will work fine:
var a = new ClassA() {Property1 = "test"}; ClassB b = (ClassB)a; Console.WriteLine(b.Property2); // output is "test"
In the first case, you can omit the type conversion explicitly and write this:
var a = new ClassA() {Property1 = "test"}; ClassB b = a;
And finally, if you want to synchronize only the properties of the parent class, you can write the converter directly to the parent:
class Parent { public string ParentProperty { get; set; } public static T1 Convert<T1>(Parent obj) where T1 : Parent, new() { var result = new T1(); result.ParentProperty = obj.ParentProperty; return result; } }
Usage (ClassA and ClassB childs of Parent):
var a = new ClassA(); a.ParentProperty = "test"; ClassB b = Parent.Convert<ClassB>(a); Console.WriteLine(b.ParentProperty);
source share