forum

Home / DeveloperSection / Forums / Issue with generics, interfaces, and casting

Issue with generics, interfaces, and casting

Takeshi Okada 2023 11-Jun-2013
Hi Expert,

I recently added an interface to some custom user controls I have implemented. The interface is pretty basic. It has one method that supports chaining:

Public Interface IMyInterface(Of T As WebControl)
    Function DoSomething() As T
End Interface

The implementations are also pretty basic:

Public Class MyCustomControl
    Inherits CompositeControl
    Implements IMyInterface(Of MyCustomControl)
Public Function DoSomething() As MyCustomControl _
    Implements IMyInterface(Of MyCustomControl).DoSomething
    ' do stuff
    Return Me
End Class

Everything works fine up to this point. The issues arise when I attempt to loop over a collection of controls that all implement the IMyInterface interface, like so:

Dim myList = New List(Of IMyInterface(Of WebControl))
myList.Add(someCustomControl)
myList.ForEach(Sub(i) i.DoSomething())
someCustomControl is a MyCustomControl which implements IMyInterface(Of MyCustomControl) instead of IMyInterface(Of WebControl).

I am getting this error on the second line (where I try to add someCustomControl):

Option Strict On disallows implicit conversions from 'MyCustomControl' to 'IMyInterface(Of WebControl)'.

Is there any way to get around this error? I am close to having it working but I do not know enough about generics to get beyond this point.

Thanks in advance for any recommendations or solutions.

Updated on 12-Jun-2013

Can you answer this question?


Answer

1 Answers

Liked By