Great Reward Great Reward - 15 days ago 13
Vb.net Question

Change inheritance class at runtime

I have two class with code like this (it's just example)

class parent1
function f(param as integer) as integer
return param +2
end function
end class
'===============================
class parent2
function f(param as integer) as integer
return param *1
end function
end class


then i want to create a class inherits of one of boot based on situation at run time. maybe like this:

class child
sub new(s as string)
'it will inherits parent1
end sub
sub new(i as integer)
'it will inherits parent2
end sub
end class


Is it possible..?

Answer

.NET languages do not support multi inheritance and you cannot change it during runtime as pointed out in all comments you got.
Instead, nice "workaround" was created for this problem called Interface. Somebody call it a "hack" solution :)

For me your problem is a problem for dependency injection.

You want have child class which can change behavior during runtime.
Create abstraction of behavior, you want to change, as interface

Public Interface IBehavior
    Function Calculate(value As Integer) As Integer
End Interface

Then create child class which takes behavior as constructor parameter

Public Class Child
    Private ReadOnly _behavior As IBehavior

    Public Sub New(behavior As IBehavior)
        _behavior = behavior
    End Sub

    Public Sub Execute(int value)
        Dim newValue As Integer = _behavior.Calculate(value)
        ' Do something else
    End Sub
End Class

Create implementations of IBehavior you want to use during runtime

Public Class SumBehavior Implements IBehavior
    Function Calculate(value As Integer) As Integer Implements IBehavior.Calculate
        Return value + 2
    End Function
End Class

Public Class MultiplyBehavior Implements IBehavior
    Function Calculate(value As Integer) As Integer Implements IBehavior.Calculate
        Return value * 2
    End Function
End Class

Then during runtime you can change behavior of Child instance based on passed parameter

Dim sum As New SumBehavior()
Dim child As New Child(sum)
child.Execute(23)

Your problem is good example of "Open-Close Principle".
- Your Child class is closed for modifications -> Do something else staff in Execute method stays unmodified
- Your child class is open for modifications -> Behavior logic can be changed without touching Child class

Comments