Generics in VB.NET
This article shows Generics in VB.NET.
In this article we will learn how to use generics in VB.NET
Generics means you can use a generic type parameter P to write a class TheList<T> and that class can be used as TheList<int>, TheList<boolean> or even TheList<MyClass> and not have to worry about runtime conversion or illegal conversion/cast errors.
- A system to define type of elements inside a class while creating object of the class.
- All such collections are provided under System.Collections.Generic namespace.
List<>
Example1:
Module Module1
Class GenericTest
Public Shared Sub Main()
Dim ar As New List(Of Integer)()
ar.Add(56)
ar.Add(55)
ar.Add(34)
Dim sum As Integer = 0
For i As Integer = 0 To ar.Count - 1
sum += ar(i)
Next
Console.WriteLine(sum)
End Sub
End Class
End Module
OUTPUT:
Example 2: Generic string List
Imports System
Imports System.Collections
Imports System.Collections.Generic
Public Class generic
Shared Sub Main(ByVal args As String())
Dim places As New List(Of String)
places.Add("A")
places.Add("B")
places.Add("C")
places.Add("d")
End Sub
End Class
Advantages of Generics:
- Type Safety. Generic types enforce compile-time type checking. Types based on Objectaccept any data type, and you must write code to check whether an inputdata type is acceptable. With generic types, the compiler can catch type mismatches before run time.
- Performance. Generic types do not have to box and unbox data, because each one is specialized for one data type. Operations based on Object must box input data types to convert them to Object and unbox data destined for output. Boxing and unboxing reduce performance.