Protected
methods can only be called from within the class that defines it. In that way, the Protected
scope is similar to Private
. If you want to call the method from another class, you will need to either change it to Public
, or wrap it in another Public
method. For instance:
Public Class MyClassWithProtectedMethod
Protected Overridable Sub MyProtectedMethod()
' ...
End Sub
Public Sub MyPublicMethod()
MyProtectedMethod()
End Sub
End Class
Public Class MyTestClass
Public Sub CallProtectedMethod()
Dim o As New MyClassWithProtectedMethod()
' Fails because method "is not accessible in this context because it is 'Protected'."
o.MyProtectedMethod()
End Sub
Public Sub CallPublicMethod()
Dim o As New MyClassWithProtectedMethod()
' Works
o.MyPublicMethod()
End Sub
End Class
The difference, though, between Private
and Protected
is that Protected
members are also accessible to derived classes. So, if you can't make modifications to the original class, since the method is Protected
, you'd still be able to make it publicly accessible via a derived class, like this:
Public Class MyClassWithProtectedMethod
Protected Overridable Sub MyProtectedMethod()
' ...
End Sub
End Class
Public Class MyDerivedClass
Inherits MyClassWithProtectedMethod
Public Sub MyPublicMethod()
MyProtectedMethod()
End Sub
End Class
Public Class MyTestClass
Public Sub CallPublicMethod()
Dim o As New MyDerivedClass()
' Works
o.MyPublicMethod()
End Sub
End Class