Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting between two types derived from the (same) interface

Tags:

c#

.net

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?

like image 307
GurdeepS Avatar asked Jan 13 '12 22:01

GurdeepS


People also ask

What is casting to an interface?

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.

What is type casting in C sharp?

Type casting is when you assign a value of one data type to another type.


2 Answers

  1. Types do not derive from an interface. They implement an interface.
  2. The fact that both an Elephant and a Spider are Animals doesn't mean that you can convert one to the other.
like image 188
Daniel Daranas Avatar answered Oct 01 '22 00:10

Daniel Daranas


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?).

like image 27
Olivier Jacot-Descombes Avatar answered Oct 01 '22 01:10

Olivier Jacot-Descombes