Classes are an essential part of any programming language in the object-oriented paradigm because of their relation to objects. This is because in an object-oriented language an object is often an instance of a class.
This article will discuss using classes in VB.NET and how to make them more useful.
Introduction
While earlier in this tutorial classes were covered, they were generally covered as ways of making a program more modular (dividing code into smaller chunks that can be used over and over again without being rewritten). This article will prove that this is not the only use of a class.
New keyword
The New
keyword is used to declare a new instance of some object. A new instance means something that has already been defined is declared as an object variable. This can be particularly useful as demonstrated later in this article.
A new class can be defined using a variable that referrences the instance such as below:
Dim newClass As New SampleClass
A new instance of a class is similar
to a variable. Any objects within the SampleClass
(or variables) and methods that are declared publicly can be accessed by other classes.
A variable can be accessed within a new class as though it was a variable with multiple properties.
Public Class SampleClass() Public Sub DisplayMessage(ByVal m As String) MsgBox(m) End Sub End Class Public Class firstClass() Sub New() Dim myClass As New SampleClass myClass.DisplayMessage("Hello world") End Sub End Class
Shared class
A static class can be defined as having shared parts within it such as methods and variables. This means that any modifications performed to the variables within the original class from any class within an application, will affect the exact sample variable. A shared class is a class whereby it contains a number of shared methods and variables. It cannot be initialised and there is just one instance of such a class.
The following example shows a class with shared properties.
Public Class firstClass Public Shared number As Integer End Class Public Class secondClass Sub New() firstClass.number = 10 End Sub End Class
Any methods within a shared class that wish to access a shared variable must themselves be shared.
Public Class firstClass Public Shared number As Integer Public Shared Sub setNumber() number = 14 End Sub End Class
Classes which contain shared methods or variables can be imported. Importing is a good way of distributing a library with static methods. An import statement always goes at the top of the file.
Imports firstClass Public Class secondClass Sub New() 'number is defined in firstClass number = 10 setNumber(15) End Sub End Class