value of type 'T' cannot be converted to...

  • Thread starter Thread starter DraguVaso
  • Start date Start date
D

DraguVaso

Hi,

I'm getting in trouble with the Generic.List(Of T).

When declaring a Shadoiws of Mybase.Add, I want to do some custom actions
with the item, and cast it to another class. The problem is that I get the
whole time this error: "value of type 'T' cannot be converted to
'clsBaseClass'".

I get it with both CType and Directcast:

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

Public Shadows Sub Add(ByVal item As T)
Dim cls As New clsBaseClass
cls = CType(item, clsBaseClass) '-> gives the error
cls = DirectCast(item, clsBaseClass) '-> gives the error
End Sub

End Class


Any help our hints would be really appreciated!

Thanks a lot in advance,

Pieter
 
DraguVaso said:
I'm getting in trouble with the Generic.List(Of T).

When declaring a Shadoiws of Mybase.Add, I want to do some custom actions
with the item, and cast it to another class. The problem is that I get the
whole time this error: "value of type 'T' cannot be converted to
'clsBaseClass'".

I get it with both CType and Directcast:

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

Public Shadows Sub Add(ByVal item As T)
Dim cls As New clsBaseClass
cls = CType(item, clsBaseClass) '-> gives the error
cls = DirectCast(item, clsBaseClass) '-> gives the error
End Sub

End Class

You see this problem because the compiler doesn't know anything about the
type T at this point, so it can't allow you to convert it into any other
type. If you are sure that the types that need to be handled will always
derive from clsBaseClass, you can use a constraint to tell the compiler so
and the cast will work. I don't normally use VB.NET, but I think the
syntax to do so should be this:

Public Class TestList(Of T As clsBaseClass)
Inherist List(Of T)
...



Oliver Sturm
 
Thanks a lot!!! You're a hero!! I finally have what I wanted with this small
piece of code! :-) Great! you made my day! hehe :-)
 
Back
Top