Encapsulation is one of the pillars of object-oriented programming, achieved through access modifiers like Private and Protected. Classic versions of Visual Basic supported only basic visibility levels, but with the transition to VB.NET, modern mechanisms similar to C# emerged.
The main task is to isolate internal implementation details from external code, including other parts of the program. Typical mistakes are related to incorrect access levels, attempts to access fields and methods outside allowed visibility areas, or misunderstandings of Protected behavior and its combinations with other modifiers.
The following modifiers are supported:
Private — access only within the current class/moduleProtected — access within the current class and all descendants (even from other assemblies)Friend — access within a single assemblyProtected Friend — access within descendants or within the assemblyExample code:
Public Class BaseClass Private Sub PrivateMethod() Console.WriteLine("PrivateMethod") End Sub Protected Sub ProtectedMethod() Console.WriteLine("ProtectedMethod") End Sub Friend Sub FriendMethod() Console.WriteLine("FriendMethod") End Sub Protected Friend Sub ProtectedFriendMethod() Console.WriteLine("ProtectedFriendMethod") End Sub End Class Public Class DerivedClass Inherits BaseClass Public Sub AccessMethods() 'PrivateMethod() 'Compilation error ProtectedMethod() 'Ok FriendMethod() 'Ok, if in the same assembly ProtectedFriendMethod() 'Ok End Sub End Class
Key features:
Private restricts the visibility to the boundaries of the classProtected works in all inherited classes across any assembliesProtected Friend combines both rulesCan you access a private field from a derived class?
No, private members are always accessible only in the class where they are declared. A derived class does not have access to private members even through reflection (unless using non-standard methods).
What is the difference between Protected and Protected Friend?
Protected — accessible only from the class and its descendants, even in other assemblies; Protected Friend — accessible either from derived classes or any code within the same assembly.
Can a protected method of a class be accessed through an instance of the base class?
No, even if the protected method is publicly visible within the descendant, it cannot be invoked on an instance of the base class from external code. Protected methods are accessible only within the body of the class or its descendant.
A developer for ease of testing makes internal fields public to access them directly from external code or unit tests. Over time, other calls begin to use these fields, relying on their internal structure.
Pros:
Cons:
Access modifiers are applied clearly, all fields are private by default, and access from outside is only through properties and public methods. For testing needs, interfaces or friend classes within the same assembly are used.
Pros:
Cons: