tags:

views:

50

answers:

1
+1  Q: 

Generic WithEvents

Error:

'WithEvents' variables can only be typed as classes, interfaces or type parameters with class constraints

Background:

Public Class Tadpole(Of T As IVisibleChanged, P As IVisibleChanged)
  Private WithEvents _Tad As T ' ERROR '
  Private WithEvents _Pole As P ' ERROR '

  Public Property Tad() As T ...

  Public Property Pole() As P ...

End Class

''' IVisibleChanged '''
Public Interface IVisibleChanged
  Property Visible() As Boolean
  Event VisibleChanged As EventHandler
End Interface

Workaround:

a. Use AddHandler to handle events defined in a structure.

EDIT

b. use Private WithEvents _Tad AsIVisibleChanged (M.A. Hanin)

c. ?

+1  A: 

I suspect this is because WithEvents cannot support value types. When you only constrain T to be IVisibleChanged you are not guaranteeing a reference type so WithEvents cannot be used. I don't know the VB syntax but if it's anything like C# you could probably do:

' Not sure of the VB syntax.
(Of T As {IVisibleChanged, Class})

This guarantees that T will not only implement IVisibleChanged by also that it won't be a struct.

Josh Einstein
the syntax is OK, thanks!
serhio