Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 36 ยท Classes and Objects

Modules, Structures, Enums and Generics

Finish the object model in Visual Basic .NET: Module versus Class, Structure value types, Enum with Flags, generic classes and methods with (Of T) and constraints, extension methods and partial classes.

Classes are not the only building blocks in VB.NET. This lesson completes the picture with modules (containers of shared code), structures (small value types), enums (named constants), generics (code that works for any type) and a few features that organize larger programs: extension methods and partial classes. Listings are VB.NET (read-only); runnable C# stand-ins use the same .NET types.

Module versus Class

A Module is a container whose members are all Shared implicitly. You call its members without a prefix, and it cannot be instantiated or inherited. It suits helper functions and the program entry point.

VB
Module MathHelpers
    Public Function Clamp(value As Integer, low As Integer, high As Integer) As Integer
        Return Math.Max(low, Math.Min(high, value))
    End Function
End Module

Console.WriteLine(Clamp(150, 0, 100))     ' 100, no class name needed

Prefer a Class with Shared members (or Public NotInheritable Class with a private constructor) when you want a named, testable utility type; prefer a normal class whenever you need instances, inheritance or interfaces. The names of module members are visible everywhere the module's namespace is imported, so keep modules small and focused.

Structure: a value type

A Structure looks like a class but is a value type: variables hold the data directly and assignment copies it. Use it for small, immutable bundles of values (a point, a color, a money amount).

VB
Public Structure Point2D
    Public ReadOnly X As Double
    Public ReadOnly Y As Double

    Public Sub New(x As Double, y As Double)
        Me.X = x
        Me.Y = y
    End Sub

    Public Function DistanceTo(other As Point2D) As Double
        Dim dx = X - other.X
        Dim dy = Y - other.Y
        Return Math.Sqrt(dx * dx + dy * dy)
    End Function
End Structure

Dim a As New Point2D(0, 0)
Dim b = a                  ' a full copy
Console.WriteLine(a.DistanceTo(New Point2D(3, 4)))    ' 5

Differences from classes: a structure cannot inherit from another structure (it may implement interfaces), it always has a parameterless default (all zero) form, and copying happens on every assignment and parameter pass. Keep structures small (about 16 bytes or less) and make them immutable; large or mutable structures cause bugs and slowdowns. Types such as Integer, Date and Decimal are structures.

C# Stand-in (C#): struct copy semantics versus class references

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Enum: named constants

An Enum gives readable names to a set of integer values:

VB
Public Enum OrderStatus
    Pending = 1
    Paid
    Shipped
    Delivered
    Cancelled = 99
End Enum

Dim status As OrderStatus = OrderStatus.Shipped
Console.WriteLine(status)                      ' Shipped
Console.WriteLine(CInt(status))                ' 3 (values continue 1, 2, 3, 4)
Console.WriteLine(status.ToString())           ' Shipped

Dim parsed As OrderStatus
If [Enum].TryParse("Paid", parsed) Then Console.WriteLine(parsed)
For Each s As OrderStatus In [Enum].GetValues(GetType(OrderStatus))
    Console.Write(s & " ")
Next

Without an explicit value, each member is the previous plus one, starting at 0. Select Case status with named members makes branches self-explanatory.

Flags enums

Mark an enum with <Flags> and give members power-of-two values to combine them with bit operations:

VB
<Flags>
Public Enum Permissions
    None = 0
    Read = 1
    Write = 2
    Execute = 4
    All = Read Or Write Or Execute
End Enum

Dim p As Permissions = Permissions.Read Or Permissions.Write
Console.WriteLine(p)                                     ' Read, Write
Console.WriteLine((p And Permissions.Write) <> 0)        ' True
Console.WriteLine(p.HasFlag(Permissions.Execute))        ' False
p = p Or Permissions.Execute
p = p And Not Permissions.Read                           ' remove a flag
C# Stand-in (C#): enum and flags enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Generics: write it once for any type

A generic type or method takes a type parameter written (Of T). The compiler checks types at compile time, and no casting is needed. The .NET collections List(Of T) and Dictionary(Of K, V) are generic.

VB
Public Class Stack(Of T)
    Private ReadOnly _items As New List(Of T)

    Public Sub Push(item As T)
        _items.Add(item)
    End Sub

    Public Function Pop() As T
        If _items.Count = 0 Then Throw New InvalidOperationException("Stack is empty.")
        Dim last = _items(_items.Count - 1)
        _items.RemoveAt(_items.Count - 1)
        Return last
    End Function

    Public ReadOnly Property Count As Integer
        Get
            Return _items.Count
        End Get
    End Property
End Class

Dim numbers As New Stack(Of Integer)
numbers.Push(10)
numbers.Push(20)
Console.WriteLine(numbers.Pop())    ' 20

Dim words As New Stack(Of String)
words.Push("hi")

Generic methods have their own parameter, and the compiler usually infers it:

VB
Function Largest(Of T As IComparable(Of T))(a As T, b As T) As T
    Return If(a.CompareTo(b) >= 0, a, b)
End Function

Console.WriteLine(Largest(3, 9))            ' 9
Console.WriteLine(Largest("pear", "apple")) ' pear

As IComparable(Of T) is a constraint: it limits which types are accepted so the body may call CompareTo. Other constraints: As Class (reference types only), As Structure (value types), As New (must have a parameterless constructor), or a base class / interface name. Combine them in braces: (Of T As {Class, IDisposable, New}).

C# Stand-in (C#): a generic class and a constrained generic method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Extension methods

An extension method adds a method to an existing type without changing it. Put it in a Module, mark it with <Extension>, and make the first parameter the type being extended:

VB
Imports System.Runtime.CompilerServices

Module StringExtensions
    <Extension>
    Public Function Shout(text As String) As String
        Return text.ToUpperInvariant() & "!"
    End Function
End Module

Console.WriteLine("hello".Shout())     ' HELLO!

LINQ is a large set of extension methods on IEnumerable(Of T).

Partial classes

Partial splits one class across several files. The compiler merges them. Windows Forms uses this so the designer-generated code (Form1.Designer.vb) stays apart from your handlers (Form1.vb):

VB
' File 1
Partial Public Class Customer
    Public Property Name As String
End Class

' File 2
Partial Public Class Customer
    Public Function Greeting() As String
        Return "Hello, " & Name
    End Function
End Class

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when you assign one Structure variable to another?

    Structures are value types, so assignment copies the whole value.
  2. 2. What is the value of CInt(OrderStatus.Shipped) when Pending = 1 and the next members have no explicit values (Paid, Shipped)?

    Members without values continue counting: Pending=1, Paid=2, Shipped=3.
  3. 3. How do you write a generic list of strings in VB.NET?

    Type arguments use the (Of T) syntax.
  4. 4. What does a constraint such as T As IComparable(Of T) allow?

    Constraints tell the compiler what members the type argument is guaranteed to have.
  5. 5. Where do extension methods have to be declared in VB.NET?

    VB extension methods live in modules and carry the Extension attribute on a method whose first parameter is the extended type.

Summary

  • A Module holds shared helpers; a Structure is a small value type that copies on assignment; an Enum names integer constants, with <Flags> for combinable options.
  • Generics ((Of T)) write type-safe code once; constraints (As IComparable(Of T), As Class, As New) restrict T.
  • Extension methods add methods to existing types; Partial classes span several files.
  • You now know the core object model and are ready for collections and LINQ.

Next: Arrays and Lists