Blazanor Blazanor - 2 years ago 163
Vb.net Question

VB return derived class instance from base class

I am trying to create a base class that can be inherited and used for daisy chaining calls but I require the returned object to be the derived class.

Consider:

Public Class MyElement
Public Function SetAttribute(name As String, value As String) As MyElement
// Set the attribute
Return Me
End Function
End Class

Public Class ExtendedElement
Inherits MyElement

Public Sub DoSomething()
// Code to do something
End Sub
End Class

// What I would like to achieve

Dim my_var As New ExtendedElement
my_var.
SetAttribute("FirstName", "Bob").
SetAttribute("LastName", "Builder").
DoSomething()


Is this kind of thing possible?

Answer Source

You have a few options, not are straight forward.

Casting

You can cast the returned value.

    Dim my_var As New ExtendedElement
    CType(my_var.
        SetAttribute("FirstName", "Bob").
        SetAttribute("LastName", "Builder"), ExtendedElement).
        DoSomething()

Overriding

You can add DoSomething in the child class and put the functionality in the parent.

Public Class MyElement
    Public Function SetAttribute(name As String, value As String) As MyElement
        Return Me
    End Function

    Public Overridable Sub DoSomething()
    End Sub

End Class

Public Class ExtendedElement
    Inherits MyElement

    Public Overrides Sub DoSomething()
        ' Do logic here
    End Sub

End Class

    my_var.
        SetAttribute("FirstName", "Bob").
        SetAttribute("LastName", "Builder").
        DoSomething()

Generics

Make the parent class a generic class to return the proper child class.

Public Class MyElement(Of T As MyElement(Of T))
    Public Function SetAttribute(name As String, value As String) As T
        Return Me
    End Function
End Class

Public Class ExtendedElement
    Inherits MyElement(Of ExtendedElement)

    Public Sub DoSomething()
        ' Do logic here
    End Sub

End Class

    Dim my_var As New ExtendedElement
    my_var.
        SetAttribute("FirstName", "Bob").
        SetAttribute("LastName", "Builder").
        DoSomething()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download