How to: Implement Interfaces in VB.NET

Implementing an interface in VB.NET is done by specification Implements. Interfaces can be implemented by classes […] and structures […]. A class or structure can implement one or more interfaces, separated by the operator , in VB.NET.
List of interfaces implemented by class/structure is given by their associated names at defining time […].

In below source code sequence, implementation of an interface in VB.NET is exemplified:

Module Module1

    Interface IOperatii
        Event Calcul(ByVal x As Integer, ByVal y As Integer)
        Function OpDiferenta(ByVal a As Integer, ByVal b As Integer)_
As Integer
        Function OpProdus(ByVal a As Integer, ByVal b As Integer) As Long
    End Interface

    Class COperatiiBin
        Implements IOperatii

        Public Event CalculOp(ByVal x As Integer, ByVal y As Integer)_
Implements IOperatii.Calcul

        Public Function Dif(ByVal a As Integer, ByVal b As Integer)_
As Integer Implements IOperatii.OpDiferenta
            Return a - b
        End Function

        Public Function Prod(ByVal a As Integer, ByVal b As Integer)_
As Long Implements IOperatii.OpProdus
            Return a * b
        End Function
    End Class
    Sub Main()
        Dim x, y, w As Integer
        x = 10
        y = 8
        Dim z As Long
        Dim OCalcul As New COperatiiBin
        z = OCalcul.Prod(x, y)
        w = OCalcul.Dif(x, y)
        MsgBox("Substraction value is: " & w & " Multiplication value is: " & z)

    End Sub

End Module

In the above example, the following issues are highlighted:

  • Defining the interface IOperatii;
  • Declaring the interface implementation by the class COperatiiBin through specification Implements IOperatii;
  • Implementation of the event by CalculOp and the two functions through methods Diff and Prod; it must be noted that at declaring time the element implemented by the interface must be specified by specifications Implements IOperatii.Calcul, Implements IOperatii.OpDiferenta and Implements IOperatii.OpProdus;
  • Event and the two methods exactly meet the prototypes defined in interface IOperatii;
  • Class does not contain other elements additional defined of the interface implemented IOperatii.

The application contains the Main procedure, and has the type Console Application.