views:

241

answers:

1

I have BaseAbstractClass(of T as WebControl) (VB Generics) which inherits WebControl.

BaseAbstractClass is inherited by ConcreteWrapper1, ConcreteWrapper2, and lastly, to shake things up a bit, ConcreteWrapper4. Each of these would inherit BaseAbstractClass using a different class inherited from WebControl.

What I would like to do is have factory that returns a ConcreteWrapper as a BaseAbstractClass(of WebControl). But whenever I try to return a new instance of a ConcreteWrapper I get a compile time conversion error.

[Edit: Code Added]

BaseAbstractClass

Public MustInherit Class BaseAbstractClass(Of T As WebControl)
    Inherits WebControl

    Protected _item As T

    Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
        _item.RenderControl(writer)
    End Sub
End Class

The other ConcreteWrappers look like this except with different CustomControl

Public Class ConcreteWrapper1
    Inherits BaseAbstractClass(Of CustomControlInheritedFromWebControl1)

    Public Sub New(ByVal control As CustomControlInheritedFromWebControl1)
        MyBase._item = control
    End Sub
End Class

Public Class CustomControlInheritedFromWebControl1
    Inherits WebControl

    //not the correct comment markers but the coloring works better
    //do stuff here... Implm not important.

End Class

My Factory

Public Class WebControlFactory

    Public Shared Function GetWebControl() As BaseAbstractClass(Of WebControl)

        Return New ConcreteWrapper1(New CustomControlInheritedFromWebControl1())

    End Function

End Class

[/Edit]

Could I get an explanation of what's going on and why that won't work (and possibly, a solution)?

Thanks!

+1  A: 

ConcreteWrapper1 does not inherit from BaseAbstractClass(of WebControl), instead it inherits from BaseAbstractClass(of T)

BAC(of WebControl) is not interchangable with BAC(of T).

If you must use inheritence, you need two levels of abstraction.

WebControl
  BAC inherits WebControl
    BAC(of T) inherits BAC
      Wrapper1 inherits BAC(of int)
      Wrapper2 inherits BAC(of string)
      Wrapper3 inherits BAC(of Foo)
      Wrapper4 inherits BAC(of Bar)

Then you may return all instances of your Wrappers as BAC.

The reason is phrased well by Zooba:

You cannot cast between generic types with different type parameters. Specialized generic types don't form part of the same inheritance tree and so are unrelated types.

David B
Aaah. Awesome. I get why that works, however, I don't entirely understand why BAC(of WebControl) and BAC(of T as WebControl) are not compatible. T is required to be a WebControl.
Wes P