Interfaces in Visual Basic .NET

Interfaces are named collections of method signatures.

Imports System

' Here's a basic interface for geometric shapes.
Public Interface IGeometry
    Function Area() As Double
    Function Perim() As Double
End Interface

' For our example we'll implement this interface on
' Rectangle and Circle types.
Public Class Rectangle
    Implements IGeometry

    Public Property Width As Double
    Public Property Height As Double

    ' To implement an interface in VB.NET, we need to
    ' implement all the methods in the interface.
    Public Function Area() As Double Implements IGeometry.Area
        Return Width * Height
    End Function

    Public Function Perim() As Double Implements IGeometry.Perim
        Return 2 * Width + 2 * Height
    End Function
End Class

Public Class Circle
    Implements IGeometry

    Public Property Radius As Double

    ' The implementation for Circle.
    Public Function Area() As Double Implements IGeometry.Area
        Return Math.PI * Radius * Radius
    End Function

    Public Function Perim() As Double Implements IGeometry.Perim
        Return 2 * Math.PI * Radius
    End Function
End Class

Public Module Program
    ' If a variable has an interface type, then we can call
    ' methods that are in the named interface. Here's a
    ' generic Measure function taking advantage of this
    ' to work on any IGeometry.
    Sub Measure(g As IGeometry)
        Console.WriteLine(g)
        Console.WriteLine(g.Area())
        Console.WriteLine(g.Perim())
    End Sub

    Sub Main()
        Dim r As New Rectangle With {.Width = 3, .Height = 4}
        Dim c As New Circle With {.Radius = 5}

        ' The Circle and Rectangle types both
        ' implement the IGeometry interface so we can use
        ' instances of these types as arguments to Measure.
        Measure(r)
        Measure(c)
    End Sub
End Module

To run the program, save it as Interfaces.vb and compile it using the VB.NET compiler:

$ vbc Interfaces.vb
$ Interfaces.exe
Rectangle
12
14
Circle
78.5398163397448
31.4159265358979

This example demonstrates how interfaces work in Visual Basic .NET. Interfaces define a contract that classes must adhere to, allowing for polymorphism and more flexible code design. The IGeometry interface is implemented by both Rectangle and Circle classes, enabling them to be used interchangeably where an IGeometry type is expected.