Home  /  Questions  /  Question



50   50
Apr 11, 2011


Private Interface Inheritance

I had a chance to see the following private interface inheritance code. Is this a common practice? Where is this being used? Thanks.

interface IAnimal 
{ 
   Eat() 
} 

class Dog : IAnimal 
{ 
   void IAnimal.Eat() 
   {...} 
} 

Dog dog = new Dog() 
dog.Eat() // error

IAnimal dog = new Dog() 
dog.Eat() // no error

 



1,128   99.9
Apr 12, 2011
What you are doing in the Dog class is explicit interface implementation, when implementing an interface this way it can not be accessed through a class instance, only through an instance of the interface. Example:

var someDog = (IAnimal) dog;
someDog.Eat(); // no error

You would for instance use explicit interface implementation to support multiple interfaces, but I myself have never found a need to use it yet. Read more about explicit interface implementation on MSDN here (and also an example where it might be useful): http://msdn.microsoft.com/en-us/library/aa288461(v=vs.71).aspx

This link might also be useful for further reading: http://stackoverflow.com/questions/143405/c-interfaces-implicit-and-explicit-implementation


Hope that helps.
 1 comment
 
Thank you. I don't see a solid argument to use this. May be it is is useful in scenarios where we are re-factoring code and has to handle multiple inheritance. --- Jacob Jacob  Apr 12, 2011

50   50
Apr 21, 2011
While implementing factory pattern...you need runtime polymorphism.

Two classes implementing same interface having different implementation, deciding object to initialize at runtime        

    Interface iShape
        Sub DrawShape()
    End Interface
    Public Class Circle
        Implements iShape

        Public Sub DrawShape() Implements iShape.DrawShape
            Debug.WriteLine("this is drawing circle")
        End Sub
    End Class

    Public Class Square
        Implements iShape

        Public Sub DrawShape() Implements iShape.DrawShape
            Debug.WriteLine("this is drawing square")
        End Sub
    End Class


Somewhere in your application,

Sub main()
 Dim s As iShape
s = New Circle
s.DrawShape()

s = New Square
s.DrawShape()
End Sub


Hope this helps.....
Saurin