Quantcast
Channel: VBForums - Visual Basic .NET
Viewing all articles
Browse latest Browse all 27392

Partial Class can change a Private function to a public one

$
0
0
Here's something interesting to me. Say you write a class that contains a private function. You can instantiate the class but not access the private function, as designed. However, say that you extend that class with a partial class. Also, in that partial class is a public function that calls the private function (since it's in the same class) and returns the results. Effectively making the private function public. Is this by design? It just seems like it could be abused. Here's an example:

Code:

Module Module1
    Sub main()
        Dim foo As New Class1
        Trace.WriteLine(foo.notpublic())
        Trace.WriteLine(foo.nowpublic())
    End Sub
End Module
Public Class Class1
    Sub New()
        MyBase.New()
    End Sub
    Private Function notpublic() As Integer
        Return 42
    End Function
End Class
Partial Class Class1
    Public Function nowpublic() As Single
        Return notpublic()
    End Function
End Class

As written, this code will not compile since the function "notpublic" is declared as private. However, if you comment or remove that line, it will compile and execute. During execution, the new function "nowpublic" in the partial class executes, calls the private function just find and returns the results to the caller.

Viewing all articles
Browse latest Browse all 27392

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>