An Interesting Use of Generics

Filed under .NET, VB Feng Shui

I was working on some validation logic today, and was getting heavily into generics in several classes, when I stumbled across an application of generics that I hadn’t see before.

Take the following sample code (granted, it’s trivial, but it should get the idea :

Public Class Form1
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim s As String = "Testing"

        Dim i As Integer = 5

        Dim f As Single = 10.7
    End Sub
End Class

Public Module Generics
    Public Sub GenericTest(Of t)(ByVal Variable As t)
    End Sub
End Module

Notice that the GenericTest function is early bound directly to 3 different variable types due to the use of generics. Just like using object type variables but without some of the stigma <g>.

Also note that GenericTest is defined in a module. I’d only seen generics as a way of defining classes before, never just a single function, and certainly not a function in a module.

Anyway, this may be old hat for many people, but I found it interesting, at the least. Not exactly sure how I might leverage it at this point, but it’s always good to have things like this in your toolbox.

Post a Comment

Your email is never published nor shared. Required fields are marked *