Friday, August 27, 2010

Implementing Two Interfaces with same method signatures.

Yes, this is absolutely possible.


Public Interface IMyInterface

    Sub MySub()
    Function MyFunc() As Integer
End Interface


Public Interface IMyInterface1
Sub MySub()
Function MyFunc() As Integer
End Interface



Public Class MyClass1
Implements IMyInterface1, IMyInterface
Public Function MyFunc() As Integer Implements IMyInterface.MyFunc
Return 14
End Function



Public Sub MySub() Implements IMyInterface.MySub
End Sub

Public Sub MySub1() Implements IMyInterface1.MySub
End Sub

Public Function MyFunc1() As Integer Implements IMyInterface1.MyFunc
Return 15
End Function


1. Which  method will be called if the method MyFunc is called on  MyClass1 ?

this will depend upon how the class is being instantiated.
if an interface is explicitely called, then the call is unambiguos :

case 1 : dim x as IMyInterface = new MyClass1()
dim i as integer = x.MyFunc()

case 2 : dim x as IMyInterface1 = new MyClass1()

dim i as integer = x.MyFunc()

in the above cases the interface is clearly specified so the relevant
method will be called.

Now consider the following :
Dim x as new MyClass1()
dim i as integer = x.MyFunc

In this case, the interface which is LAST DECLARED in the "Implements" list will be refered.
Public Class MyClass1

       Implements IMyInterface1, IMyInterface

Since IMyInterface appears last in the list, it will be refered.

Can I remove any of the methods implementation ?
No (at least in VB) implementation of both methods is required, other wise the program will not compile.




Public Sub MySub2() Implements IMyInterface1.MySub
End Sub

End Class

No comments:

Post a Comment

 using Microsoft.AspNetCore.Mvc; using System.Xml.Linq; using System.Xml.XPath; //<table class="common-table medium js-table js-stre...