ProgrammingVB.NET Middle/Lead Developer

Explain how the Friend access modifier works in Visual Basic, provide an example of its use, and specify situations where Friend is preferable to other modifiers.

Pass interviews with Hintsage AI assistant

Answer.

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:

  • For classes/methods that should be accessible to other parts of the application but not to external modules/libraries.
  • For implementing access patterns (e.g., testing internal components).

Trick question.

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:

  • Friend — accessible only within its own assembly (regardless of inheritance).
  • Protected — accessible only in derived classes (regardless of assembly).
  • A method with Friend access will not be available to derived classes outside of the current assembly. If access is needed in both inheritance and within the assembly — use Protected Friend.
Protected Friend Sub MyMethod() ' Accessible within the assembly and for inherited classes outside the assembly End Sub

Examples of real errors due to lack of understanding of the topic.


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.