Ad space (banner)
๐Ÿ”ทVB.NET Lessons
Lesson 51 / 68

Writing general functions with generics

This lesson covers writing general functions with VB.NET's generics, with the aim of producing flexible code that handles several types.

Writing Function Name(Of T As Constraint)(...) defines a generic function whose type is decided later. One function then serves several types instead of one per type.

In the sample code, Function Larger(Of T As IComparable)(a As T, b As T) As T compares both the numbers in Larger(3, 7) and the strings in Larger("apple", "banana"). The As IComparable constraint restricts it to types that can be compared.

A common early stumble is why the type parameter needs a constraint at all. A bare T is not guaranteed to have a method such as CompareTo(), so As IComparable narrows it to types that do.

In professional work, generics are used widely for collection classes such as List(Of T) and for shared logic meant to serve many types.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run VB.NET directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)