Creating Classes, Structures, and Enumerations – Visual Basic .NET

Almost all applications require creating one or more custom types, each with multiple properties and methods. In fact, proper object-oriented development design would place the bulk of the programming logic in these custom types.

For example, if you were creating an application that allowed you to edit a document, you would create a Document class. To update the document, you might call the Document.Update method. Depending on the purpose, you might create custom structures or enumerations rather than a custom class.

This page describes how to create custom classes, structures, and enumerations.

To create a custom class, use the Class keyword. Within the class, you can:

  • Declare properties using the Public or Private keywords. Properties are variables within your class.
  • Declare constructors using the New keyword in Visual Basic or by specifying a method using the class name in C#. Constructors are called to create a new instance of your class. You can provide multiple constructors to allow the calling method to provide different arguments when creating the class.
  • Declare methods within your class. Standard methods can be called after creating an instance of your class, and static methods can be called without creating an instance of your class. You can override standard methods, such as ToString.

The code sample below introduces you to the concept of creating a custom class. You will get more practice working with custom classes throughout this course.

The following code sample demonstrates how to create a new class named Person, create two instances of that class, access member properties, and then call a member method. Structures are a composite of other value types. The .NET Framework includes many structures, such as System.Drawing.Point. The Point class contains two value type properties: X and Y integers, as well as a number of methods.

' Declare the class Person

Class Person

    ' Declare three public variables

    Public firstName As String

    Public lastName As String

    Public dateOfBirth As DateTime

    ' Provide a constructor with no arguments

    Public Sub New()

    End Sub

    ' Provide a constructor with three arguments

    Public Sub New(ByVal newFirstName As String, ByVal newLastName As String, ByVal newDateOfBirth As DateTime)

        ' Assign the public variables using the arguments

        firstName = newFirstName

        lastName = newLastName

        dateOfBirth = newDateOfBirth

    End Sub

    ' Override the standard ToString() method

    Public Overloads Overrides Function ToString() As String

        ' Return the first and last names

        Return (firstName & " ") + lastName

    End Function

End Class

Private Sub Main()

    ' Create an instance of Person

    Dim david As New Person()

    ' Define the person's name and birthdate

    david.firstName = "David"

    david.lastName = "Probst"

    david.dateOfBirth = New DateTime(1985, 5, 1)

    ' Create an instance of person using the constructor that takes arguments

    Dim chris As New Person("Chris", "Preston", New DateTime(1974, 1, 3))

    ' Display the names of the two instances

    Console.WriteLine(david)

    Console.WriteLine(chris)

End Sub

You can work with structures similar to the way you work with other classes. However, because structures are value types, they can be used more efficiently in some circumstances.

To create a structure, use the Structure keyword in Visual Basic or the struct keyword in C#.

For example, the following code creates a type that represents the 360 degrees of a compass. In this case, adding one degree to 359 degrees should return the value to 0, and subtracting one degree from 0 degrees should set the value to 359. The + and – operators detect when calls attempt to pass these boundaries and set the correct value.

Structure Compass

    ' Private field only accessible from within the structure

    Private _val As Integer

    ' Public field used to grant external access to _val

    Public Property Value() As Integer

        Get

            Return _val

        End Get

        Set(ByVal value As Integer)

            If value > 359 Then

                Me.Value = value - 359 - 1

            Else

                If value < 0 Then

                    Me.Value = 360 + value

                Else

                    _val = value

                End If

            End If

        End Set

    End Property

    ' Allow output as a string

    Public Overloads Overrides Function ToString() As String

        Return Value.ToString()

    End Function

    ' Allow output as an integer

    Public Function ToInteger() As Integer

        Return Value

    End Function

    ' Allow inclusion in addition operations

    Public Shared Operator +(ByVal arg1 As Compass, ByVal degrees As Integer) As Compass

        arg1.Value += degrees

        Return arg1

    End Operator

    ' Allow inclusion in subtraction operations

    Public Shared Operator -(ByVal arg1 As Compass, ByVal degrees As Integer) As Compass

        arg1.Value -= degrees

        Return arg1

    End Operator

End Structure

Given that implementation of the Compass class, you could write the following console application to create an instance of the class and then perform addition and subtraction operations to represent turning:

' Create an instance of Compass

Dim direction AsNew Compass()

' Set the direction to West

direction.Value = 90

Console.WriteLine("Direction: " & direction)

' Turn around, towards the left

direction.Value -= 180

Console.WriteLine("Direction: " & direction)

' turn right

direction.Value += 90

Console.WriteLine("Direction: " & direction)

Enumerations act like array constants. You should create an enumeration any time you want to be able to select one of several pre-defined values using friendly names within the development environment.

For instance, consider the following simple code sample. You could accomplish the same thing using an array of strings, but using enumerations is easier to develop with because Visual Studio can catch any typos before you compile your application.

Enum Titles

     Mr

     Ms

     Mrs

     Dr

 End Enum 

Dim t As Titles = Titles.Dr 

' Displays "Dr."  

Console.WriteLine("{0}.", t)

Return to the .NET Framework Fundamentals Table of Contents.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>