Chapter 24. Defining Class Methods and Events

Lesson 23 explains how to create a class and give it properties. In this lesson you learn how to add the remaining two key pieces of a class: methods and events.


A method is simply a subroutine or function in the class that other parts of the program can execute. The following code shows how the Turtle drawing class described in Lesson 23 might implement its Move method:

' Make the Turtle move the indicated distance in its current direction.
Public Sub Move(ByVal distance As Integer)
    ' Calculate the new position.
    Dim radians As Double = Direction * Math.PI / 180
    Dim newX As Integer = CInt(X + Math.Cos(radians) * distance)
    Dim newY As Integer = CInt(Y + Math.Sin(radians) * distance)

    ' Draw to the new position.
    Using gr As Graphics = Graphics.FromImage(Canvas)
        gr.DrawLine(Pens.Blue, X, Y, newX, newY)
    End Using

    ' Save the new position.
    X = newX
    Y = newY
End Sub


You can download the Turtle example program from the book's web site (at or as part of the Lesson24 folder and follow along in its code as you read through this lesson.

The method takes as a parameter the distance it should move. It uses the Turtle's current position and direction to figure out where this move will terminate. It uses some graphics code to draw a line from the current position to the new one (don't worry about the details) and finishes by saving the new position.

That's all there is to adding a method to a class. ...

Get Stephens' Visual Basic® Programming 24-Hour Trainer now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.