Home > DeveloperSection > Forums > Issue with generics, interfaces, and casting
Takeshi Okada
Takeshi Okada

Total Post:89

Posted on    June-11-2013 7:28 AM

 VB.Net VB.Net 

 1 Reply(s)
 956  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.


Total Post:604

Posted on    June-12-2013 7:54 AM

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).

Don't want to miss updates? Please click the below button!

Follow MindStick