It is not possible to simply cast one object other type even if thay have one parent, because thay maybe have different interfaces.
You need to implement explicit or implitic operator of ChildA (or ChildB).
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 conversings operators following code will work fine:
var a = new ClassA() {Property1 = "test"};
ClassB b = (ClassB)a;
Console.WriteLine(b.Property2); // output is "test"
In first case you can omit explicitely type conversion and write just like this:
var a = new ClassA() {Property1 = "test"};
ClassB b = a;
And finally if you want to synchronize only properties of parent class you can write converter directly in 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;
}
}
Using (ClassA and ClassB childs of Parent):
var a = new ClassA();
a.ParentProperty = "test";
ClassB b = Parent.Convert<ClassB>(a);
Console.WriteLine(b.ParentProperty); // output is "test"