posted on Thursday, January 27, 2005 10:09 AM
by
roydictus
Fun with Interfaces, Part 2
Remember the post on Fun With Interfaces? Let's take this a step further...
The model from last time was the following:

ICouple inherits from IAlice and IBob; if you instantiate Carol, who implements IAlice and IBob, you can call the methods on both IAlice and IBob, but Carol does not automagically implement ICouple. However, if Carol was defined to implement ICouple, you could cast her to IAlice and to IBob and that would work:
ICouple carolOne = new Carol();
string carolA = carolOne.AliceSays();
string carolB = carolOne.BobSays();
carolA = ((IAlice) carolOne).AliceSays();
carolB = ((IBob) carolOne).BobSays();
This works, but interestingly enough, at development time IntelliSense can't really figure it out -- it does display AliceSays() in the list of methods, but not BobSays(). But it does compile and run just fine.
Now, let's make the model a bit more complex:

We still have the same interfaces, but now we have a new type called OddCouple which implements both ICouple and IBob.
OddCouple can implement both these methods:
public
virtual string AliceSays()
{
return "Alice";
}
public virtual string BobSays()
{
return "Bob";
}
Question 1: What will this do at compiletime, and at runtime?
The following code is expected to work, and in fact it does:
ICouple theTwo = new OddCouple();
string whatBobSays = theTwo.BobSays();
string whatAliceSays = theTwo.AliceSays();
The code in this example also works, as you'd expect:
IBob mrBob = new OddCouple();
whatBobSays = mrBob.BobSays();
After all, OddCouple implements IBob explicitly. Now, what happens when you try the following?
IAlice mrsAlice = new OddCouple();
whatAliceSays = mrsAlice.AliceSays();
Question 2: To make matters even more complicated, we have another type called OdderStill which inherits from OddCouple and explicitly declares that it implements IAlice. What will this do at compiletime, and at runtime?
Question 3: Do I have too much time on my hands?