Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 3.7Access modifiers

Part 3.7Access modifiers

An access modifier is a keyword that defines what access is permitted to a specific class, module, function, sub routine or variable.

Whilst only the latter word has been discussed as of yet, the concept of an access modifier in this article will be used to describe any of them. However, it will ultimately focus on variables.

There are just four access modifiers in VB.NET:

  • Public
  • Protected
  • Friend
  • Private

The two most common are Public and Private because when creating a form, the class is Public and it's control methods are Private.

VB.NET access modifiers

Public

Public is the exact representation of the word - the object is exposed to any project. This means that any project can place a referrence and run methods, access variables and so on from within the project.

For program extensions written as a Class Library that is compiled to a .NET DLL, this is very useful as it allows other users of the library to access parts of it.

As shown in the diagram, a public object can be accessed from both inside and outside of the project.

VB.NET
Public sample As String
						

Protected

Protected is a bit more tricky to understand. A protected object can be accessed within the class it was created within or a class derived from it (inheritited). The object is limited to the assembly (program or project) it was created within.

Classes cannot be given the protected access modifier - only the objects, such as variables, inside the class can be given this keyword.

VB.NET
Protected sample As String
						

Friend

A friend object is one which can be access within the assembly and only within the assembly it was created in. This is how assemblies have hidden methods and classes, for instance, for encryption purposes.

A friend object in a DLL can be used to create additional functions into a class that can be used by other methods from within the assembly.

For instance, a class called A has a friend method called 1 and a public method called 2. B, which comes from within the same project, can access both 1 and 2. C which comes from another project can access method 2 only.

VB.NET
Friend sample As String
				

Private

A private method can be accessed from within the same class and their parent must be public. Private is the most closed that an object can be - that is there is no exposure outwith the class at all.

VB.NET
Private sample As String
				
Feedback 👍
Comments are sent via email to me.