0

I have the interface IPet and in another project I have the class Dog which inherits from IPet.
In Dog I have the method Bark() but not in IPet.
In the project of IPet I have also the class PetSimulation in which I have an instance of IPet.
Now I want to make something like this:

IPet myDog = new IPet("Rex");  
myDog.Bark();  

But IPet does not have the method Bark() and that should remain that way because other classes such as Cat and Horse are also inherit from IPet but don't have the method Bark either.
Also I can't do something like this:

Dog myDog = new Dog("Rex");  

because Dog is in another project.

Is there any way for me to call the Method Bark of the subclass Dog over the interface IPet without implementing the method there?

phant0m
  • 16,595
  • 5
  • 50
  • 82
Torben L.
  • 73
  • 1
  • 10

4 Answers4

2

Short answer: No.

Slightly longer answer:

You can test the IPet to see if it is a Dog, like this:

Dog dog = myDog as Dog;
if (dog != null)
{
    dog.Bark();
}

Note that you can't directly create an interface like you do in the question, except in very rare circumstances.

Community
  • 1
  • 1
pwny
  • 41
  • 2
  • I see... That does not work for me because at that point i do not have access to Dog, only to IPet. With the implemetation: The original code is much longer and more complicated. I wanted to make it as simple as possible. – Torben L. Nov 02 '12 at 15:21
1

You cant. But you could make an interface IDog with the method Bark, that would inherit from IPet

public interface IPet
{

}

public interface IDog : IPet
{
    void Bark();    
}

public class Dog : IDog
{
    public void Bark()
    {
        Console.WriteLine("Wouff!");    
    }
}
mortb
  • 9,361
  • 3
  • 26
  • 44
  • So this would lead to you beeing able to call the method Bark. But you still can't create an IDog object in a projects / assembly without having a reference to a project / assembly that contains an actual implementation -- a class that *derives* from IDog. The interface has no "code body" it is a contract and it just defines what behavior is available, not how it is performed. – mortb Nov 05 '12 at 11:06
0

You would need to cast myDog to Dog in order to access methods that only that class has:

IPet myDog = new IPet("Rex");  
((Dog)myDog).Bark();  

If you implement Bark in the interface then it will be required for all classes that implement it.

Can you access Dog by adding a reference to Dog's project?

user15741
  • 1,392
  • 16
  • 27
  • No because the Project of _Dog_ is the main project and already has an reference to the project of _IPet_. So i cant add a reference the other way round... – Torben L. Nov 02 '12 at 15:15
0

If you really cannot access the Dog class and are working in .NET 4+ you could try

dynamic dog = new ...
dog.Bark()
flq
  • 22,247
  • 8
  • 55
  • 77