I have an interface and two types that derive from it.
However, I cannot do the following:
B objectB = (B) objectA
Where B derives
An object is assignable to an ancestor (direct or indirect base type) or to an interface it implements, but not to siblings (i.e. another type deriving from a common ancestor); however, you can declare your own explicit conversions:
class FooObject : IObject
{
public string Name { get; set; }
public int Value { get; set; }
public static explicit operator FooObject(BarObject bar)
{
return new FooObject { Name = bar.Name, Value = bar.Value };
}
}
class BarObject : IObject
{
public string Name { get; set; }
public int Value { get; set; }
public static explicit operator BarObject(FooObject bar)
{
return new BarObject { Name = bar.Name, Value = bar.Value };
}
}
Now you can write
var foo = new FooObject();
var bar = (BarObject)foo;
or
var bar = new BarObject();
var foo = (FooObject)bar;
without getting errors.
You can also create implicit conversions, if it feels natural. E.g. int is implicitly convertible to double: int i = 5; double x = i;.
(This is also an answer to the closed question How do I cast Class FooObject to class BarObject which both implement interface IObject?).