Introduction to Class Programming

Method of a Class

In addition to class member (property) data. Your custom class can also include Sub and Function procedures, which are commonly  known as methods of the class.  A method of a class represent some standard operations on the class itself (properties).  As you know, the difference between Sub and Function, is that Sub does not return any value, whereas Function method returns a value.  But Visual Basic lets you invoke a function and discard its return value.  In our example class, you could easily add a routine that calculate the Student Age

Function Age() As Integer
' Returns the age in years between 2 dates.
' Doesn't handle negative date ranges i.e. BirthDate > Now()
    If Month(Now()) < Month(BirthDate) Or _
      (Month(Now()) = Month(BirthDate) And _
      Day(Now()) < Day(BirthDate)) Then
        Age = Year(Now()) - Year(BirthDate) - 1
    Else
        Age = Year(Now()) - Year(BirthDate)
    End If
End Function

As you can see in our example, if you are within the class module, you don't need the dot syntax to refer to the properties of the current instance. In addition, if you refer to a Public name for a property (BirthDate) instead of the corresponding Private member variable (m_BirthDate), Visual Basic executes the Property Get procedure as if the property were referenced from outside the class.

'In your client form
MsgBox "Student Age : " & objStudent.Age

Now let create another function, that checks the validity of YearLevel.  We will make this function to be Private meaning that this procedure can only be called from within the module.

'In your Student class module
' Private method of a class, cannot be used outside
Private Function IsValidYearLevel(level As String) As Boolean
  Dim varTemp As Variant
  Dim found As Boolean
  
  For Each varTemp In Array("Freshmen", "Sophomore", "Junior", "Senior")
    If InStr(1, level, varTemp, vbTextCompare) Then
        found = True
        Exit For
    End If
  Next
  
  IsValidYearLevel = found
End Function
        
'In Property Let YearLevel
Property Let YearLevel(ByVal strNewValue As String)
   If Not IsValidYearLevel(strNewValue) Then Err.Raise 5
   m_YearLevel = strNewValue
End Property

In other words, you cannot call this method in your client application.  In fact, you cannot see a Private function in IntelSense technology of Visual Basic as shown below.

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Perl - The only language that looks the same before and after RSA encryption.” - Keith Bostic