I have classes structured like this:
Public MustInherit Class A
' several properties
End Class
Public Class B
Inherits A
' several properties
End Class
Public MustInherit Class C
Protected _X As A
Public ReadOnly Property X As A
Get
Return _X
End Get
End Property
End Class
Public Class D
Inherits C
Private _X As B
Public ReadOnly Property X As B
Get
Return _X
End Get
End Property
Sub New
_X = New B
End Sub
End Class
Is there a modifier I can use on property X in class D which will cause X to be returned as B from an instance of D and A from an instance of D that is evaluated as C?
i.e.
Dim d As New D
Response.Write((d.X Is Nothing) & "<br>")
Dim c As C = d
Response.Write(c.X Is Nothing)
In both cases I want X to not be Nothing
I realize I could modify D as follows:
Public Class D
Inherits C
Private __X As B
Public ReadOnly Property X As B
Get
Return __X
End Get
End Property
Sub New
__X = New B
_X = __X
End Sub
End Class
Is there a cleaner solution?
You should avoid new code using
Shadows, but if you really need this construct, I get the results you’re expecting with just the addition ofMyBase._X=_XtoD‘sNew(Option 1) which could also be done by having aNewinCthatDcalls, then does the opposite assignment_X = DirectCast(MyBase._X, B)(Option 2).Of course another option, depending upon your actual intention, is to drop the
Private _X As BinDand just cast the_XtoBin your shadowedX. (Option 3)Here is my code with Options 1 and 2 commented out and currently performing Option 3.