Question

I work in VB.NET v2

I have an interface IMyInterface and this interface implements a method MyMethod.

I have an object MyObjectBase. This object contains a(the same) method MyMethod.

1) If now I do MyObject Inherits MyObjectBase Implements IMyInterface need I to redefine? (shadow, override) MyMethod in the MyObject class?

2) What now if instead the MyMethod method I have an MyEvent event?

Thanks.

Was it helpful?

Solution

In VB.NET, you need to manually associate your interface contract with your implementations. Have a look at the following example:

Interface MyInterface
    Sub Foo()
End Interface

Class TestClass
    Implements MyInterface

    Public Sub Test() Implements MyInterface.Foo
        Console.WriteLine("Test")
    End Sub

    Public Sub Foo()
        Console.WriteLine("Foo")
    End Sub
End Class

Then have a look at the following code and its output:

Dim x As New TestClass()
x.Foo()                           ' Output: Foo '
Dim y As MyInterface = x
y.Foo()                           ' Output: Test '

This has the advantage that implementing an interface does not restrict you in naming your function as you want to. The disadvantage is that you have to explicitly associate your class methods with your interface declarations using the Implements keyword.


So much about an explanation. Now let me get to your problem: Since you cannot make Button implement IVisibleChanged, you can do something like that:

Private Event MyVisibleChanged() Implements IVisibleChanged.VisibleChanged

Private Sub RethrowVisibleChanged() Handles MyBase.VisibleChanged
    RaiseEvent MyVisibleChanged()
End Sub

MyBase is a VB.NET keyword referring to the superclass. Likewise, in the case of MyMethod, you can do

Private Sub MyInterfaceMethod() Implements IMyInterface.Method
    MyBase.Method()
End Sub

This might seem like unnecessary extra work, but in a way, it makes sense: Button.VisibleChanged and IVisibleChanged.VisibleChanged might be events with two completely different semantics, who just happen to have the same name (after all Button does not implement IVisibleChanged). With your code, you explicitly create a connection between those two.

OTHER TIPS

It's because you implement your child class that you have to redefine it. I believe if you just inherit from the base case, which is implemented anyway, you won't have to if you don't need it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top