Reputation: 63
Maybe somebody can help me out please, i can imagine it is a common need: I have a base and a child class. The base class has a property named "hello". Now I need to add extended functionality in the property Set of the child - How can I achive that?
A code sample for further explanation:
Base Class:
Public MustInherit Class Base
Private pHello as String = ""
Public Property Hello As String
Get
Return pHello
End Get
Set(ByVal value As String)
pHello = value
'DoSomethingInBaseClass()
MsgBox "BaseClass calling!" 'Just for testing
End Set
End Property
End Class
Child Class
Public Class Child
Inherits Base
Public Property Hello As String
Get
Return MyBase.Hello
End Get
Set(ByVal value As String)
'DoSomethingInCHILDClass()
MsgBox "ChildClass calling!" 'Just for testing
End Set
End Property
End Class
Property Set in Main
Public Class Main
Public Sub DoIt()
Dim InstChild as new Child
InstChild.Hello = "test"
End Sub
End Class
Basically what i want is, when setting the property, that I first get the Child MessageBox and then the Base MessageBox.
Sure I need to add a keyword in the Property definition(s). I played around with Shadows and Overrides, but either I get only the Child or only the Base Message.
Is there a way to get both?
Thank you very much!
Upvotes: 2
Views: 1507
Reputation: 676
I recommend doing the work in an overridable function. This way you can have the child class do its work then call MyBase.overriddenFunction().
For example:
Base Class
Public MustInherit Class Base
Private pHello as String = ""
Public Property Hello As String
Get
Return pHello
End Get
Set(ByVal value As String)
pHello = value
doSomething()
MsgBox "BaseClass calling!" 'Just for testing
End Set
End Property
Private Overridable Sub doSomething()
'Do base class stuff
End Sub
End Class
Child Class
Public Class Child
Inherits Base
Public Property Hello As String
Get
Return MyBase.Hello
End Get
Set(ByVal value As String)
doSomething()
MsgBox "ChildClass calling!" 'Just for testing
End Set
End Property
Private Overrides Sub doSomething()
'Do child class stuff
MyBase.doSomething()
End Sub
End Class
Upvotes: 1
Reputation: 176
The problem is in the child class. Instead of returning myBase.hello
just return Me.hello
.
because at first me.hello
of the child class will be equal to the hello
of the base class
. So when you override the property, at the base class it will remain the same, and it will only change on the child class.
so in order to get both of you should call: Base.Hello.get()
and Child.Hello.get()
Upvotes: 0