In C#, can you give a good example of why you would implement an interface on a base class and re-implement that interface on a derived class, rather than making the base class methods virtual.
For example:
interface IMakesNoise
{
void Speak();
}
class Cat : IMakesNoise
{
public void Speak()
{
Console.WriteLine("MEOW");
}
}
class Lion : Cat, IMakesNoise
{
public new void Speak()
{
Console.WriteLine("ROAR");
}
}
To test the behavior:
Cat cat = new Cat();
Cat lion = new Lion();
// Non virtual calls, acts as expected
cat.Speak();
lion.Speak();
// Grabbing the interface out is 'virtual' in that it grabs the most derived interface implementation
(cat as IMakesNoise).Speak();
(lion as IMakesNoise).Speak();
This will print out:
MEOW
MEOW
MEOW
ROAR
UPDATE: For more clarification about the why, the reason is I am implementing a compiler and I want to know the reason that C# chose this implementation of interfaces.
I have looked at this question.
Interface inheritance in ComVisible classes in C#
and this
C# exposing to COM - interface inheritance
As I understand, if you have two objects and want them to be visible through COM, both should explicitly inherit from the required interface.
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