Visual Basic .NET - Generics in VB.NET
Generics allow you to create classes, methods, interfaces, and delegates with a placeholder for the data type. Instead of writing separate code for integers, strings, or other data types, you write one generic definition and specify the type when using it. This makes your program more reusable, type-safe, and efficient.
In VB.NET, generics are commonly used with collections. For example, List(Of Integer) stores only integers, and List(Of String) stores only strings. The (Of T) syntax represents a type parameter. The letter T is commonly used to represent a generic type, but you can use any valid name.
Example:
Dim numbers As New List(Of Integer)
numbers.Add(10)
numbers.Add(20)
Here, the list can only store integers. If you try to add a string, the compiler will show an error. This improves type safety and reduces runtime errors compared to older collections like ArrayList, which could store mixed data types.
You can also create your own generic class:
Public Class Box(Of T)
Public Value As T
End Class
Usage:
Dim intBox As New Box(Of Integer)
intBox.Value = 100
Dim strBox As New Box(Of String)
strBox.Value = "Hello"
In this example, the same Box class works with different data types. This avoids rewriting similar code multiple times.
Generics provide three main benefits:
-
Type Safety – Errors are caught at compile time instead of runtime.
-
Code Reusability – One class or method works with multiple data types.
-
Better Performance – No need for boxing and unboxing when working with value types.
Generics are an important concept in modern VB.NET programming because they make applications more structured, reliable, and efficient.