Issue with generics, interfaces, and casting

Total Post:89


 1666  View(s)
Rate this:
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.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.
  1. Re: Issue with generics, interfaces, and casting

    Hi Takeshi,

    You will need to cast the object before adding it:

    myList.Add(CType(someCustomControl, IMyInterface(Of WebControl)))

    You may also want to concider making the interface not generic and your "DoWork" method return type as the interface itself.

    Public Interface IMyInterface
        Function DoSomething() As IMyInterface
    End Interface

    When you have to specify the type in the interface definition it kind of takes away from the power of interfaces (not having to know about the implementation).


Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.