vb.nettypeofdirectcast

DirectCast error


I have the following code:

Imports System.Collections.ObjectModel

Public Class clsCellListExtender

    Public Class List(Of T)
        Inherits Collection(Of T)

        Private _iID As Integer = 0

        Protected Overrides Sub InsertItem(index As Integer, item As T)
            'your checks here

            If TypeOf (item) Is clsCell Then
                _iID += 1
                Dim nCell As clsCell = DirectCast(item, clsCell)
                nCell.TempID = _iID
            End If

            MyBase.InsertItem(index, item)
        End Sub

    End Class

End Class

When I try to compile it, the compiler tells me that "T cannot be converted to clsCell" in the line

Dim nCell As clsCell = DirectCast(item, clsCell)

Can somebody please tell me what I did wrong?

Thank you!


Solution

  • I think the problem here is that T is not restricted to an object. You need something to be an object or in fact any ancestor of clsCell class (it's just that Object is an ancestor of all types, so DirectCast always works with it). Consider the following example:

    Dim p As String
    If TypeOf p Is Integer Then
    
    End If
    

    The compiler will complain in this case:

    Expression of type 'String' can never be of type 'Integer'.

    In your case compiler cannot verify if there is always an inheritance relationship between T and clsCell. In most cases they won't be one, so you cannot use DirectCast.

    The solution for you would be using a different cast operator, such as a TryCast, at least it does not cause a compile time error. Also best if you explained what you meant to do here, because List(Of T) is a standard type in .NET, so making another is good for creating confusion.

    I would expect it to fail on TypeOf line though, using the same logic. Maybe someone else can elaborate on this.