VB.NET Interface Example

Illustration

How can you use an Interface in your VB.NET program to implement polymorphic behavior based on an object's type? With an Interface, you can specify that a Function is required on all classes that implement it. Then, you can access objects through the Interface type but call the derived Functions.

This VB tutorial shows how to use Interface types. Interfaces are abstractions that are applied to many Class types.

Example

This program declares the IValue Interface, which requires one method Render. The Content and Image classes both implement IValue; they implement IValue.Render in different ways. Notice how the Implements keyword is used for both classes and functions.

Program that uses Interface [VB.NET]

Interface IValue
    Sub Render()
End Interface

Class Content : Implements IValue
    Public Sub Render() Implements IValue.Render
	Console.WriteLine("Content.Render")
    End Sub
End Class

Class Image : Implements IValue
    Public Sub Render() Implements IValue.Render
	Console.WriteLine("Image.Render")
    End Sub
End Class

Module Module1
    Sub Main()
	' Create dictionary of Interface type instances.
	Dim dict As Dictionary(Of String, IValue) = New Dictionary(Of String, IValue)
	dict.Add("cat1.png", New Image())
	dict.Add("image1.png", New Image())
	dict.Add("home.html", New Content())

	' Get value from Dictionary and call their Render methods.
	Dim value As IValue = Nothing
	If dict.TryGetValue("cat1.png", value) Then
	    value.Render()
	End If

	' Again.
	If dict.TryGetValue("home.html", value) Then
	    value.Render()
	End If
    End Sub
End Module

Output

Image.Render
Content.Render
Question and answer

Sub Main description. What happens in the Main entry point? A new Dictionary is created and three String keys are added. They point to two Image class instances and one Content class image. Then, the TryGetValue function is invoked twice. When the IValue is retrieved from the Dictionary, the Render sub is called. This results in the specialized implementation being called from the general Interface type.

Dictionary Examples TryGetValue Example

Summary

The VB.NET programming language

Interfaces in VB.NET introduce another level of abstraction that you can apply to your program logic. By declaratively implementing an Interface in many Classes, you can then refer to instances of those Classes through the Interface type. Then, you can call the Interface functions, which will invoke the specialized functions from the Classes. This makes it possible to streamline the logic in your program through data-directed design.

VB.NET Tutorials
.NET