Blazanor
Blazanor

Reputation: 175

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?

Upvotes: 0

Views: 819

Answers (2)

the_lotus
the_lotus

Reputation: 12748

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

Upvotes: 2

Quima
Quima

Reputation: 914

You can do something like this:

Dim MyVar as new ExtendedElement
Ctype(MyVar.SetAttribute("FirstName", "Bob"). _
      SetAttribute("LastName", "Builder"), ExtendedElement).DoSomething()

Upvotes: 0

Related Questions