The Friend modifier in Visual Basic defines that a class member (method, property, variable) is accessible within the same assembly but not outside of it. It is analogous to internal in C#. This level of access is useful for ensuring the "encapsulation" of the internal implementation of code while keeping public APIs open.
Example usage:
' Inside one project/assembly Friend Class InternalHelper Friend Sub Log(message As String) Console.WriteLine(message) End Sub End Class
Calling methods of the InternalHelper class will only be possible within the current assembly.
When to use Friend:
What is the difference between the Friend and Protected access modifiers? Can a method declared as Friend be visible in a derived class in another assembly?
Answer:
Protected Friend Sub MyMethod() ' Accessible within the assembly and for inherited classes outside the assembly End Sub
Story
In a large project, all the logic of supporting classes was declared as Public, which opened them to external integrators. Changing to Friend eliminated the risk of using internal methods outside the module and simplified architecture maintenance.
Story
Due to an access error (used Protected instead of Friend), helper methods were unavailable for modular tests that were placed in the same project but outside the class hierarchy. Changed to Friend to support easier testing.
Story
One developer tried to use Friend to expose methods to a plug-in loaded from another assembly. As a result, the plugins did not have access to the necessary methods. The solution was to implement interfaces with Public methods, using Friend only for internal needs.