<< Back to VBNET
VB.NET Class Examples
Review Classes and their syntax, applying the Me, MyClass and Friend keywords.Class. Programs are complex. A class is one part of a program. It is self-contained. When we modify a class, other parts of the program are not affected.
StructureA program in VB.NET may also contain Modules and Namespaces. But the Class is the core unit—things like Strings and Lists are special classes.
First example. This program introduces an Example Class. In the Class, we have a Private field of type Integer. We also have a constructor—the New() Sub.
Value: Finally we have the Value() Function, which returns an expression based on a field. It is Public, so can be called from Main.
Step 1: In the Main Sub, control flow begins. We create an instance of the Example Class—an Example now exists on the managed heap.
Step 2: We access the Example instance (called "x") and invoke its Value Function. This returns 2, and we print the result.
VB.NET program that uses Class
Class Example
Private _value As Integer
Public Sub New()
_value = 2
End Sub
Public Function Value() As Integer
Return _value * 2
End Function
End Class
Module Module1
Sub Main()
' Step 1: create a new instance of Example Class.
Dim x As Example = New Example()
' Step 2: call Value Function on the Example.
Console.WriteLine(x.Value())
End Sub
End Module
Output
4
Me qualifier. With the Me qualifier, we specify a member directly on the current instance of the class. If the class is derived, any further derived classes are ignored.
Info: With "Me," we can qualify whether we mean to indicate a local variable, or a member on the current class.
Here: We use Me.species to reference the field on the Bird class. The variable "species" is the parameter to the New Sub.
VB.NET program that uses Me qualifier
Class Bird
Private species As Integer
Public Sub New(ByVal species As Integer)
' Print Me and not-Me variables.
Console.WriteLine("ME: {0}/{1}", Me.species, species)
' The Me qualification makes it clear we are assigning a field.
Me.species = species
End Sub
End Class
Module Module1
Sub Main()
Dim bird = New Bird(10)
End Sub
End Module
Output
ME: 0/10
Inherits. With Inherits, one class can inherit from another class. This means it gains all the fields and procedures from the parent class.
Class A: Let's begin by looking at Class A: this class contains a field (_value) as well as a Sub (Display()).
Class B, C: These 2 classes use the Inherits keyword and are derived from Class A. They provide their own constructors (New).
Info: You can see the New B() and New C() will do slightly different things when called.
Display: Class B and Class C inherit Display from Class A. When b.Display() and c.Display() are called, the A.Display Sub is invoked.
VB.NET program that uses Inherits keyword
Class A
Public _value As Integer
Public Sub Display()
Console.WriteLine(_value)
End Sub
End Class
Class B : Inherits A
Public Sub New(ByVal value As Integer)
MyBase._value = value
End Sub
End Class
Class C : Inherits A
Public Sub New(ByVal value As Integer)
MyBase._value = value * 2
End Sub
End Class
Module Module1
Sub Main()
Dim b As B = New B(5)
b.Display()
Dim c As C = New C(5)
c.Display()
End Sub
End Module
Output
5
10
MyClass versus Me. The MyClass and Me qualifiers have an important difference. MyClass refers to the current class, and Me refers to the current instance—it could be called "MyInstance."
MyClass: With MyClass, a method on the current instance of the class is called. So in the Animal class, Animal.Test is invoked.
Me: This references the current instance, not the current class. So Cat.Test is invoked, because we have a Cat object.
VB.NET program that uses MyClass, Me qualifiers
Class Animal
Public Sub Enter()
' Use MyClass and Me to call subroutines.
MyClass.Test()
Me.Test()
End Sub
Public Overridable Sub Test()
Console.WriteLine("Animal.Test called")
End Sub
End Class
Class Cat : Inherits Animal
Public Overrides Sub Test()
Console.WriteLine("Cat.Test called")
End Sub
End Class
Module Module1
Sub Main()
Dim cat As Cat = New Cat()
cat.Enter()
End Sub
End Module
Output
Animal.Test called
Cat.Test called
Shared. Some fields in a Class are not tied to a Class instance. Only one instance is needed. Shared is used on fields to make one field shared among all Class instances.
Tip: A Public Shared field can be used in the same way as a global variable. This is useful for storing settings.
SharedVB.NET program that uses Shared field
Class Test
Public Shared _v As Integer
End Class
Module Module1
Sub Main()
Test._v = 1
Console.WriteLine(Test._v)
Test._v = 2
Console.WriteLine(Test._v)
End Sub
End Module
Output
1
2
Shared Sub. These methods are not tied to a Class instance. A Shared Sub can be called with a composite name. Next, the Write Sub inside the Test class is called with "Test.Write()".
VB.NET program that uses Shared Sub
Class Test
Public Shared Sub Write()
Console.WriteLine("Shared Sub called")
End Sub
End Class
Module Module1
Sub Main()
Test.Write()
End Sub
End Module
Output
Shared Sub called
Partial. This modifier specifies that a class is specified in multiple declarations. With Partial, were open a class and add new parts to it. A Class can span multiple files.
VB.NET program that uses Partial
Module Module1
Partial Class Test
Public Sub X()
Console.WriteLine("X")
End Sub
End Class
Partial Class Test
Public Sub Y()
Console.WriteLine("Y")
End Sub
End Class
Sub Main()
' Invoke methods on the partial class.
Dim t As Test = New Test()
t.X()
t.Y()
End Sub
End Module
Output
X
Y
Friend. This modifier makes a member (like a Class, Sub or Function) unavailable outside the present assembly. An assembly is a physical file that contains compiled code.
Here: We specify that Display() is a Friend Sub. So it is Public inside the assembly, but not available outside.
VB.NET program that uses Friend
Class Item
Friend Sub Display()
Console.WriteLine("Friend Class used")
End Sub
End Class
Module Module1
Sub Main()
' The Display Sub is public if we are in the same assembly.
Dim local As Item = New Item()
local.Display()
End Sub
End Module
Output
Friend Class used
Object. All classes inherit from Object, the ultimate base class. We thus can cast all variables to an Object. The object class provides some helpful methods.
Equals: This compares the contents of two objects. Implementations from derived classes are used.
GetType: This returns a Type object based on the type of the current object. GetType is similar to VarType.
GetHashCode: Returns a hash code integer based on the content of the instance. Derived implementations are often present.
ToString: Converts an Object to a string representation. The exact string returned varies by implementation.
VB.NET program that uses Object
Class Example
' An empty Example class: it automatically inherits from Object.
End Class
Module Module1
Sub Main()
' Create instance of the Example class.
Dim x As Example = New Example()
' The class inherits from Object, so we can cast it to an Object.
Dim y As Object = x
' ... This method is from Object.
Console.WriteLine(y.GetHashCode())
' When we call GetHashCode, the implementation from Object is used.
Console.WriteLine(x.GetHashCode())
End Sub
End Module
Output
46104728
46104728
Interface. Instead of Inherits, we could use an Interface. We use the Implements keyword with Interfaces. An Interface is a contract—a set of demands that compliant types fill.
InterfaceMeanwhile: A base class is a core template of data and functionality. Base classes are not the same as interfaces.
Note: With Inherits, we implement complex object models that can closely represent, in a declarative way, a type framework.
MustInherit. This provides an alternative to the Interface type. It modifies a Class so that it can only be used as a base Class. The class no longer can be directly instantiated.
And: A MustInherit Class is essentially a template that is part of the classes that inherit from it.
MustInherit
VarType. This function is equivalent to the GetType function. It returns a Type reference for an object instance. Its syntax is different from GetType's.
VarTypeModules. A Module has shared data. The Main Subroutine is found in a Module. All fields in a Module are shared, meaning they are not part of an instance. Modules are not types.
ModuleNamespaces. With namespaces, we have another way to organize programs. Namespaces contain other types like classes, but are not objects.
NamespaceNotes, composite names. In programming languages, a name such as "MyBase._value" is called a composite name. We access the base class (A) and the field on the base class (_value).
A summary. Classes are essential building blocks. A class is a reference type: it is allocated on the managed heap. It can have Functions, Subs, and data members.
Related Links:
- VB.NET Nullable
- VB.NET Convert Char Array to String
- VB.NET Object Array
- VB.NET File.ReadAllText, Get String From File
- VB.NET Compress File: GZipStream Example
- VB.NET Console.WriteLine (Print)
- VB.NET File.ReadLines Example
- VB.NET AddressOf Operator
- VB.NET Recursion Example
- VB.NET Recursive File Directory Function
- VB.NET Regex, Read and Match File Lines
- VB.NET Regex.Matches Quote Example
- VB.NET Regex.Matches: For Each Match, Capture
- VB.NET Convert String, Byte Array
- VB.NET File Size: FileInfo Example
- VB.NET File Handling
- VB.NET String.Format Examples: String and Integer
- VB.NET SyncLock Statement
- VB.NET TextInfo Examples
- VB.NET Array.Copy Example
- VB.NET HtmlEncode, HtmlDecode Examples
- VB.NET HtmlTextWriter Example
- VB.NET Stack Type
- VB.NET Func, Action and Predicate Examples
- VB.NET Function Examples
- VB.NET GoTo Example: Labels, Nested Loops
- VB.NET Array.Find Function, FindAll
- VB.NET HttpClient Example: System.Net.Http
- VB.NET DataColumn Class
- VB.NET DataGridView
- VB.NET DataSet Examples
- VB.NET DataTable Select Function
- VB.NET DataTable Examples
- VB.NET Attribute Examples
- VB.NET OpenFileDialog Example
- VB.NET Benchmark
- VB.NET BinaryReader Example
- VB.NET BinarySearch List
- VB.NET BinaryWriter Example
- VB.NET Regex.Replace Function
- VB.NET Regex.Split Examples
- VB.NET Regex.Match Examples: Regular Expressions
- VB.NET Convert ArrayList to Array
- VB.NET Array Examples, String Arrays
- VB.NET ArrayList Examples
- VB.NET Boolean, True, False and Not (Return True)
- VB.NET Nothing, IsNothing (Null)
- VB.NET Directive Examples: Const, If and Region
- VB.NET Do Until Loops
- VB.NET Do While Loop Examples (While)
- VB.NET Array.Resize Subroutine
- VB.NET Chr Function: Get Char From Integer
- VB.NET Class Examples
- VB.NET IndexOf Function
- VB.NET Insert String
- VB.NET Interface Examples (Implements)
- VB.NET 2D, 3D and Jagged Array Examples
- VB.NET Enum.Parse, TryParse: Convert String to Enum
- VB.NET Remove HTML Tags
- VB.NET Remove String
- VB.NET Event Example: AddHandler, RaiseEvent
- VB.NET Excel Interop Example
- VB.NET StartsWith and EndsWith String Functions
- VB.NET Initialize List
- VB.NET Number Examples
- VB.NET Optional String, Integer: Named Arguments
- VB.NET Replace String Examples
- VB.NET Exception Handling: Try, Catch and Finally
- VB.NET Enum Examples
- VB.NET Enumerable.Range, Repeat and Empty
- VB.NET Dictionary Examples
- VB.NET Double Type
- VB.NET LSet and RSet Functions
- VB.NET LTrim and RTrim Functions
- VB.NET Alphanumeric Sorting
- VB.NET PadLeft and PadRight
- VB.NET String.Concat Examples
- VB.NET String
- VB.NET Math.Abs: Absolute Value
- VB.NET Array.IndexOf, LastIndexOf
- VB.NET Remove Duplicate Chars
- VB.NET If Then, ElseIf, Else Examples
- VB.NET ParamArray (Use varargs Functions)
- VB.NET Integer.Parse: Convert String to Integer
- VB.NET ThreadPool
- VB.NET Process Examples (Process.Start)
- VB.NET TimeZone Example
- VB.NET Path Examples
- VB.NET ToArray Extension Example
- VB.NET ToCharArray Function
- VB.NET Stopwatch Example
- VB.NET Button Example
- VB.NET StreamReader ReadToEnd Function
- VB.NET ByVal Versus ByRef Example
- VB.NET StreamReader Example
- VB.NET StreamWriter Example
- VB.NET String.Compare Examples
- VB.NET Cast: TryCast, DirectCast Examples
- VB.NET String Constructor (New String)
- VB.NET String.Copy and CopyTo
- VB.NET Math.Ceiling and Floor: Double Examples
- VB.NET Math.Max and Math.Min
- VB.NET WebClient: DownloadData, Headers
- VB.NET Math.Round Example
- VB.NET Math.Truncate Method, Cast Double to Integer
- VB.NET Reverse String
- VB.NET Structure Examples
- VB.NET Sub Examples
- VB.NET Substring Examples
- VB.NET Convert Dictionary to List
- VB.NET Convert List and Array
- VB.NET Convert List to String
- VB.NET Convert Miles to Kilometers
- VB.NET Property Examples (Get, Set)
- VB.NET Remove Punctuation From String
- VB.NET Queue Examples
- VB.NET Const Values
- VB.NET Remove Duplicates From List
- VB.NET IComparable Example
- VB.NET ReDim Keyword (Array.Resize)
- VB.NET Contains Example
- VB.NET IEnumerable Examples
- VB.NET IsNot and Is Operators
- VB.NET String.IsNullOrEmpty, IsNullOrWhiteSpace
- VB.NET ROT13 Encode Function
- VB.NET StringBuilder Examples
- VB.NET Image Type
- VB.NET Val, Asc and AscW Functions
- VB.NET String.Empty Example
- VB.NET String.Equals Function
- VB.NET VarType Function (VariantType Enum)
- VB.NET With Statement
- VB.NET WithEvents: Handles and RaiseEvent
- VB.NET String Length Example
- VB.NET ToList Extension Example
- VB.NET ToLower and ToUpper Examples
- VB.NET TextBox Example
- VB.NET ToString Overrides Example
- VB.NET ToTitleCase Function
- VB.NET Convert String Array to String
- VB.NET Iterator Example: Yield Keyword
- VB.NET Mid Statement
- VB.NET Mod Operator (Odd, Even Numbers)
- VB.NET Convert String to Integer
- VB.NET Module Example: Shared Data
- VB.NET Integer
- VB.NET Keywords
- VB.NET Lambda Expressions
- VB.NET LastIndexOf Function
- VB.NET String Join Examples
- VB.NET Multiple Return Values
- VB.NET MustInherit Class: Shadows and Overloads
- VB.NET Namespace Example
- VB.NET KeyValuePair Examples
- VB.NET Environment.NewLine: vbCrLf
- VB.NET Levenshtein Distance Algorithm
- VB.NET Shared Function
- VB.NET Shell Function: Start EXE Program
- VB.NET Sleep Subroutine (Pause)
- VB.NET Sort Dictionary
- VB.NET Exit Statements
- VB.NET LINQ Examples
- VB.NET List Examples
- VB.NET Extension Method
- VB.NET Select Case Examples
- VB.NET MessageBox.Show Examples
- VB.NET Timer Examples
- VB.NET TimeSpan Examples
- VB.NET BackgroundWorker
- VB.NET String Between, Before and After Functions
- VB.NET CStr Function
- VB.NET DataRow Field Extension
- VB.NET DataRow Examples
- VB.NET DateTime Format
- VB.NET Char Examples
- VB.NET DateTime.Now Property (Today)
- VB.NET DateTime.Parse: Convert String to DateTime
- VB.NET DateTime Examples
- VB.NET Decimal Type
- VB.NET HashSet Example
- VB.NET Hashtable Type
- VB.NET Fibonacci Sequence
- VB.NET XmlWriter, Create XML File
- VB.NET File.Copy: Examples, Overwrite
- VB.NET File.Exists: Get Boolean
- VB.NET Path.GetExtension: File Extension
- VB.NET Tuple Examples
- VB.NET Trim Function
- VB.NET TrimEnd and TrimStart Examples
- VB.NET Word Count Function
- VB.NET Word Interop Example
- VB.NET For Loop Examples (For Each)
- VB.NET XElement Example
- VB.NET Truncate String
- VB.NET Sort Number Strings
- VB.NET Sort Examples: Arrays and Lists
- VB.NET SortedList
- VB.NET SortedSet Examples
- VB.NET Split String Examples
- VB.NET Uppercase First Letter
- VB.NET XmlReader, Parse XML File
- VB.NET ZipFile Example
- VB.NET Array.Reverse Example
- VB.NET Random Lowercase Letter
- VB.NET Byte Array: Memory Usage
- VB.NET Byte and Sbyte Types
- VB.NET Char Array
- VB.NET Random String
- VB.NET Random Numbers
- VB.NET Async, Await Example: Task Start and Wait
- VB.NET Choose Function (Get Argument at Index)
- VB.NET Sort by File Size
- VB.NET Sort List (Lambda That Calls CompareTo)
- VB.NET List Find and Exists Examples
- VB.NET Math.Sqrt Function
- VB.NET Loop Over String: For, For Each
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf