Question

I need to call the Protected Overridable sub OnValidatingPassword from my code behind but I can't because telling me that is protected (which it is)
Is someone to knows how to do it?
Or from the other hand... did we have the code inside this sub in order to implement it?
As a new sub of course.

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top