This documentation is archived and is not being maintained.

7.5 Classes

Visual Studio .NET 2003

A class is a data structure that may contain data members (constants, variables, and events), function members (methods, properties, indexers, operators, and constructors), and nested types. Classes are reference types. The following example shows a class that contains each kind of member:

Imports System

Class AClass

    Public Sub New()
        Console.WriteLine("Constructor")
    End Sub

    Public Sub New(ByVal value As Integer)
        MyVariable = value
        Console.WriteLine("Constructor")
    End Sub

    Public Const MyConst As Integer = 12
    Public MyVariable As Integer = 34

    Public Sub MyMethod()
        Console.WriteLine("MyClass.MyMethod")
    End Sub

    Public Property MyProperty() As Integer
        Get
            Return MyVariable
        End Get

        Set (ByVal value As Integer)
            MyVariable = value
        End Set
    End Property

    Default Public Property Item(ByVal index As Integer) As Integer
        Get
            Return 0
        End Get

        Set (ByVal value As Integer)
            Console.WriteLine("Item(" & index & ") = " & value)
        End Set
    End Property

    Public Event MyEvent()

    Friend Class MyNestedClass
    End Class 
End Class 

The following example shows uses of these members:

Imports System

Module Test

    ' Event usage.
    Dim WithEvents aInstance As AClass

    Sub Main()
        ' Constructor usage.
        Dim a As AClass = New AClass()
        Dim b As AClass = New AClass(123)

        ' Constant usage.
        Console.WriteLine("MyConst = " & AClass.MyConst)

        ' Variable usage.
        a.MyVariable += 1
        Console.WriteLine("a.MyVariable = " & a.MyVariable)

        ' Method usage.
        a.MyMethod()

        ' Property usage.
        a.MyProperty += 1
        Console.WriteLine("a.MyProperty = " & a.MyProperty)
        a(1) = 1

        ' Event usage.
        aInstance = a
    End Sub 

    Sub MyHandler() Handles aInstance.MyEvent
        Console.WriteLine("Test.MyHandler")
    End Sub 
End Module

There are two class-specific modifiers, MustInherit and NotInheritable. It is invalid to specify them both.

ClassDeclaration ::=
   [ Attributes ] [ ClassModifier+ ] Class Identifier LineTerminator
   [ ClassBase ]
   [ TypeImplementsClause+ ]
   [ ClassMemberDeclaration+ ]
   End Class LineTerminator
ClassModifier ::= AccessModifier | Shadows | MustInherit | NotInheritable

See Also

7.5.1 Class Base Specification | 7.2 Interface Implementation | 7.5.2 Class Members | 7.1 Value Types and Reference Types | 7.3 Primitive Types | 7.4 Enumerations | 7.6 Structures | 7.7 Standard Modules | 7.8 Interfaces | 7.9 Arrays | 7.10 Delegates | Class Statement (Visual Basic Language Reference) | Classes: Blueprints for Objects (Visual Basic Language Concepts)

Show: