Alex Rivera | Logout

Casting between two types derived from the (same) interface

Asked 2012-01-13T22:26:47.700
16

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?

Edit
Report

2 Answers

1

You need to cast as the interface.

interface IBase { }
class A : IBase { }
class B : IBase { }

With this, the only thing the two types have in common is the interface members. B might have items that A does not.

A a = new A();
B b = new B();

IBase aBase = a;
IBase bBase = b;

You can then call anything on the IBase Interface.

answered 2012-01-13T22:30:37.163
0

Imagine the following setup:

public interface Human
{
    bool Male { get; }
}

public class Man : Human
{
    public bool HasABeard { get { return true; } }

    public bool IsMale { get { return true; } }
}

public class Woman : Human
{
    public bool IsMale { get { return false; } }

    public List<Pair<Shoe>> Shoes { get; set; }
}

What would you expect the compiler to produce from the following code? What will the output be?

Man a;
Woman b = new Woman();
a = (Man)b;

Console.WriteLine(a.HasABeard ? "Beard ON" : "Beard OFF");
answered 2012-01-13T22:38:37.200

Your Answer