Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing an interface in a base and derived class

Tags:

c#

interface

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.

like image 436
Trevor Sundberg Avatar asked Oct 23 '25 14:10

Trevor Sundberg


1 Answers

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.

like image 164
Viktor Arsanov Avatar answered Oct 26 '25 03:10

Viktor Arsanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!