1

I'm not exactly sure how to ask this question, but basically what I want to do is access the abstract methods from IDog. Consider this:

    static void Main(string[] args)
    {
        IDog dog = new Dog();
        dog.CatchFrisbee();
        dog.Speak("Bark") // error -> no implementation
        Console.ReadLine();
    }

    public class Dog : Animal, IDog
    {
        public void CatchFrisbee()
        {
            Console.WriteLine("Dog Catching Frisbee");
        }
    }
    public abstract class Animal : IAnimal
    {
        public void Speak(string sayWhat)
        {
            Console.WriteLine(sayWhat);
        }

        public void Die()
        {
            Console.WriteLine("No Longer Exists");
        }
    }
    public interface IDog
    {
        void CatchFrisbee();
    }
    public interface IAnimal
    {
        void Die();

        void Speak(string sayWhat);
    }

From my static void Main, I would like to be able to call dog.Speak() but I can't because it's not implemented in IDog. I know I can easily access Speak() from my derived classes but is it possible to access it from the implemenation or would that be a bad design?

0

2 Answers 2

6

Assuming that all IDogs are IAnimals, declare IDog as implementing IAnimal

public interface IDog : IAnimal
Sign up to request clarification or add additional context in comments.

6 Comments

@spender Thanks for the answer! I'm trying to become more disciplined in OOP practices and ran into an issue where I thought this would be beneficial. Is this something that is common because I was speaking to another developer and she asked why I wanted to do this as if it was a bad design. Thanks again!
Could you explain the principle that keeps Dog from inheriting Speak() since it Dog inherits Animal and Animal implements Speak()?
@pseudocoder because IDog isn't an IAnimal, Dog is. Dog can be cast to IAnimal or Animal, but IAnimal can't be cast to IDog or the other way around.
@pseudocoder Yes, it would be available if it was Dog
@pseudocoder yes, see the other answers, they are valid and work, but the architecture is the root of the problem.
|
1

You could perform a cast:

 ((Animal) dog).Speak("Bark"); 

Or take advantage of multiple interface inheritance:

public interface IDog : IAnimal
{
    void CatchFrisbee();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.