I have a problem in a VB.Net class library which I have simplified greatly down to the following...
Public MustInherit Class TargetBase
End Class
Public Class TargetOne
Inherits TargetBase
End Class
Public Class TargetTwo
Inherits TargetBase
End Class
Public Class TargetManager
Public Sub UpdateTargets(ByVal Targets As List(Of TargetBase))
For Each objTarget As TargetBase In Targets
UpdateTarget(objTarget)
Next
End Sub
Private Sub UpdateTarget(ByVal Value As TargetOne)
End Sub
Private Sub UpdateTarget(ByVal Value As TargetTwo)
End Sub
End Class
This will not compile due to a syntax error on the UpdateTarget(objTarget)
line - Overload resolution failed because no accessible 'UpdateTarget' can be called without a narrowing conversion
So I changed the For-Each loop to use Object instead of TargetBase...
For Each objTarget As Object In Targets
UpdateTarget(objTarget)
Next
This now compiles but I get a run-time error - Public member 'UpdateTarget' on type 'TargetManager' not found.
So I took the obvious next step of making the 2 UpdateTarget() overloads Public (instead of Private).
Public Sub UpdateTarget(ByVal Value As TargetOne)
End Sub
Public Sub UpdateTarget(ByVal Value As TargetTwo)
End Sub
This now works!
I can just about understand why changing it to Object would work but why must these methods be made Public when I am only calling them from within the same class - I would rather they weren't available outside this class.
Can anybody explain this?
Thanks in advance (and sorry for the length of this question!)
Additional Thanks for everyones answers so far. Ive got the workaround (make UpdateTarget methods Public) that makes it work. Another workaround would be to do a TypeOf check on objTarget and then DirectCast before calling UpdateTarget, like...
For Each objTarget As Object In Targets
If TypeOf objTarget Is TargetOne Then
UpdateTarget(DirectCast(objTarget, TargetOne))
ElseIf TypeOf objTarget Is TargetTwo Then
UpdateTarget(DirectCast(objTarget, TargetTwo))
End If
Next
This will also work - I posted the question because I really wanted to understand why changing visibility of UpdateTarget from Private to Public got rid of the run-time error, totally against my understanding!