dotNET
dotNET

Reputation: 35400

Implement an interface in partial class

I need all my TableAdapters to implement a custom interface. The problem is that some of the members defined by the interface reside in the DataSet's designer file, which I don't want to (and shouldn't) alter, as that code will be regenerated automatically. I can't relocate those members to my code file either for the same reason. What's my way out of it?

Upvotes: 2

Views: 1328

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54427

When you implement an interface, the members you declare do not have to have the same names as the members of the interface and they don't have to be public. Let's say that you have this designer-generated class:

Partial Public Class SomeClass

    Public Sub FirstMethod()
        Console.WriteLine("FirstMethod")
    End Sub

    Public Sub SecondMethod()
        Console.WriteLine("SecondMethod")
    End Sub

End Class

and you want it to implement this interface:

Public Interface ISomeInterface

    Sub FirstMethod()

    Sub ThirdMethod()

End Interface

Notice that the interface has a method named FirstMethod but SomeClass already has a method named FirstMethod. You can add your own partial class to implement the interface like this:

Partial Public Class SomeClass
    Implements ISomeInterface

    Private Sub FirstMethodInternal() Implements ISomeInterface.FirstMethod
        Me.FirstMethod()
    End Sub

    Public Sub ThirdMethod() Implements ISomeInterface.ThirdMethod
        Console.WriteLine("ThirdMethod")
    End Sub

End Class

The method that implements ISomeInterface.FirstMethod is not named FirstMethod so it doesn't clash with the existing method with that name and it is also Private so it cannot be accessed from outside using a reference of type SomeClass. Using a reference of type ISomeInterface is another matter though. If you use code like this:

Dim sc As ISomeInterface = New SomeClass

sc.FirstMethod()
sc.ThirdMethod()

you'll find that the FirstMethodInternal method of your SomeClass object gets invoked and, in turn, invokes the FirstMethod method of the same object. Try running that code and placing breakpoints on the FirstMethod and FirstMethodInternal methods to prove it to yourself.

Upvotes: 3

Related Questions