What are the behavior differences for the Previous
Property of Other1
and Other2
Class.
Note than the return type of the overloaded Previous
Property of Other2
has been changed to Other2
while it stays as Base
for Other1
.
Public Class Base
Private _Previous as Base
Protected Overridable ReadOnly Property Previous As Base
Get
Return _Previous
End Get
End Property
Public Sub New(Previous as Base)
_Previous = Previous
End Sub
End Class
Public Class Other1
Inherits Base
Private _Parent as SomeType
Protected Overrides ReadOnly Property Previous As Base
Get
Return _Parent.Previous.Something
End Get
End Property
Public Sub New(Parent as SomeType)
MyBase.New(Nothing)
_Parent = Parent
End Sub
End Class
Public Class Other2
Inherits Base
Private _Parent as SomeType
Protected Overloads ReadOnly Property Previous As Other2
Get
Return _Parent.Previous.Something
End Get
End Property
Public Sub New(Parent as SomeType)
MyBase.New(Nothing)
_Parent = Parent
End Sub
End Class
After one of my comment to Jim Wooley's answer, "it look like it Shadows the overloaded property." I saw the light in this article.
So, the Overloads in the Other2 class act some more like shadowing than override. There is one of the comments in the article that is particularly instructive :
The confusion arises because the keyword "Overloads" isn't what a C# programmer considers an overload in the traditional OO sense. It's a type of hiding that is specific to VB.Net. You can actually swap the keyword SHADOWS with OVERLOADS in most cases, and the behavior is the same. The difference is when you have a base class with multiple overloaded method signatures. If you declare a method in a subclass with a matching name, and the SHADOWS keyword, it will hide EVERY overload of that method in the base class. If you use the OVERLOADS keyword instead, it will only hide the base class method with an identical signature.
Typically you would use Overloads when you are supplying different input parameters. Overrides replaces the functionality. In your case, you want Overrides in Other2 not Overloads. While properties can take parameters other than the value, it is best to not provide them and to use methods rather than properties when passing other values:
Public Class OldMath
Public Overridable Function DoSomething(val1 As Integer) As Integer
Return val1 + val1
End Function
End Class
Public Class NewMath
Public Overrides Function DoSomething(val1 As Integer) As Integer
Return val1 * val1
End Function
Public Overloads Function DoSomething(val1 As Integer, val2 As Integer) As Integer
Return val1 * val2
End Function
End Class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With