I have an interface and two types that derive from it.
However, I cannot do the following:
B objectB = (B) objectA
Where B derives from Interface1 (I am making up the name of classes but the point still stands), and likewise for objectA (which is of type A). I get the following error message:
Cannot cast expression of type A to B.
Both types are deriving from the interface, what am I missing?
You can access the members of an interface through an object of any class that implements the interface. For example, because Document implements IStorable , you can access the IStorable methods and property through any Document instance: Document doc = new Document("Test Document"); doc.
Type casting is when you assign a value of one data type to another type.
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?).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With