ISSUE WITH GENERICS, INTERFACES, AND CASTING

Takeshi Okada

Total Post:89

Points:629
Posted by  Takeshi Okada
VB.Net 
 1232  View(s)
Ratings:
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.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.
  1. AVADHESH PATEL

    Post:604

    Points:4228
    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).

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!