How to find what type or class an instance is based on
Sunday, 15 November 2009

Its alway very useful in VB.NET/ASP.NET to be able to find out whether or not a class is of a particular type, or is inherited.

You can do this by using the typeof keyword in VB.NET

for example if we were overloading an Arraylist, but wanting to check that an add is of the correct type when we could use the following snippet

Imports Microsoft.VisualBasic

Namespace Shop
    Public Class OrderLinesCollection
        Inherits ArrayList

        Public Overrides Function Add(ByVal value As Object) As Integer
            If TypeOf value Is OrderLine Then
                Return MyBase.Add(value)
            Else
                Throw New NotSupportedException("You can only add OrderLines to this collection")
            End If

        End Function

    End Class
End Namespace
Last Updated ( Sunday, 13 December 2009 )