How to VB.NET Access Specifiers

Access specifiers are used to control the accessibility or visibility of classes, methods, properties, and other members within a program. Access specifiers determine which parts of a program can access and interact with specific members.

There are four access specifiers available in VB.NET:

Public

The Public access specifier allows unrestricted access to a member from anywhere in the program, including outside the defining class or assembly.

Public Class MyClass Public myPublicVariable As Integer Public Sub MyPublicMethod() ' Code here End Sub End Class Dim obj As New MyClass() obj.myPublicVariable = 10 ' Accessing public variable obj.MyPublicMethod() ' Accessing public method

Protected

The Protected access specifier allows access to a member within the defining class and any derived classes. Protected members are not accessible from outside the class hierarchy.

Public Class MyBaseClass Protected myProtectedVariable As Integer Protected Sub MyProtectedMethod() ' Code here End Sub End Class Public Class MyDerivedClass Inherits MyBaseClass Public Sub AccessProtectedMember() myProtectedVariable = 10 ' Accessing protected variable MyProtectedMethod() ' Accessing protected method End Sub End Class

Friend (Default)

The Friend access specifier is the default if no access specifier is specified. It allows access to a member within the defining assembly (project). It is similar to the "internal" access specifier in C#.

Public Class MyClass Friend myFriendVariable As Integer Friend Sub MyFriendMethod() ' Code here End Sub End Class Dim obj As New MyClass() obj.myFriendVariable = 10 ' Accessing friend variable obj.MyFriendMethod() ' Accessing friend method

Private

The Private access specifier restricts access to a member within the defining class only. Private members are not accessible from outside the class.

Public Class MyClass Private myPrivateVariable As Integer Private Sub MyPrivateMethod() ' Code here End Sub End Class Dim obj As New MyClass() obj.myPrivateVariable = 10 ' Error: Private variable not accessible obj.MyPrivateMethod() ' Error: Private method not accessible

These access specifiers help in encapsulating and controlling the visibility of members, allowing for proper encapsulation and modular design. By choosing the appropriate access specifier, you can ensure that the members of your class are accessible and used only where necessary, enhancing the security and maintainability of your code.