Let's have some fun with interfaces. This posting was
inspired by a recent call for help from a colleague.
Say you have two basic interfaces, IAlice and IBob, as in
the following code:
using
System;
namespace
FunWithInterfaces
{
public interface IAlice
{
string AliceSays();
}
}
and
using
System;
namespace
FunWithInterfaces
{
public interface IBob
{
string BobSays();
}
}
And say you have a third interface, ICouple, which just
inherits from these two:
using
System;
namespace
FunWithInterfaces
{
public interface ICouple : IAlice, IBob
{
}
}
Now, so far, so good. What if you had a class, Carol --
who speaks for both Alice and Bob -- who implements IAlice and IBob, like
so:
using
System;
namespace
FunWithInterfaces
{
/// <summary>
/// Carol speaks for both Alice and Bob --
/// but does she speak for the
couple?
/// </summary>
public
class Carol : IAlice, IBob
{
public string AliceSays()
{
return "Bob, come
home!";
} // AliceSays
public
string BobSays()
{
return "I can't, watching
sports!";
}
}
}
Does Carol also speak for the couple? That
is, is she automatically seen by the .Net Framework as implementing ICouple?
What happens when you do this?
ICouple somebody = (ICouple)
new Carol();
Try to find the answer before trying it out :-)