views:

142

answers:

1

Hi,

I have an user control in our library that I need to inherit and make some update to it. The issue that I'm having right now is that I cannot instantiate the new user control directly. I have to call a method in the library that will create and pass an instance of the user control. Please check sample code below.

I tried to use casting and I got InvalidCastException. I think that's because the second requires more storage than the first.

Thanks in advance for helping on this.

Namespace ProjectA.Components

    Public Class MainClass

        Public Function CreateCustomControl() As CustomControl
            Dim cc As CustomControl = Activator.CreateInstance(Of CustomControl)()
            Return cc
        End Function

    End Class

    Public Class CustomControl
        Inherits System.Windows.Forms.UserControl
    End Class

End Namespace

Namespace ProjectB

    Public Class ExtendedCustomControl
        Inherits ProjectA.Components.CustomControl
    End Class

    Public Class MainForm
        Inherits System.Windows.Forms.Form

        Private Sub CreateInstance()
            Dim i As New ProjectA.Components.MainClass
            Dim myControl As ExtendedCustomControl = i.CreateCustomControl
            ' InvalidCastException is thrown.
        End Sub

    End Class

End Namespace
A: 

It's because you aren't instantiating an ExtendedCustomControl, you are instantiating a CustomControl. Activator.CreateObject is just creating the base class. You can't upcast something unless it actually IS of the class you're casting to.

Maybe you want CreateCustomControl() to take a System.Type and then pass it into Activator.CreateInstance instead? That way you might be able to make what you want?

Dave Markle