EXTENSION METHODS

Extension methods allow you to add new methods to an existing class without rewriting it or deriving a new class from it. To make an extension method, place the method in a code module and decorate its declaration with the Extension attribute. The first parameter determines the class that the method extends. The method can use that parameter to learn about the item for which the method was called. The other parameters are passed into the method so it can use them to perform its chores.

For example, the following code adds a MatchesRegexp subroutine to the String class:

' Return True if a String matches a regular expression.
<Extension()>
Public Function MatchesRegexp(the_string As String,
 ByVal regular_expression As String) As Boolean
    Dim reg_exp As New Regex(regular_expression)
    Return reg_exp.IsMatch(the_string)
End function

The Extension attribute tells Visual Basic that this is an extension method. The method’s first parameter is a String so this method extends the String class. The second parameter is a regular expression. The method returns True if the String matches the regular expression.

The following code shows how a program might use this method to decide whether the string stored in variable phone_number looks like a valid 7-digit United States phone number:

if Not phone_number.MatchesRegexp("^[2-9]\d{2}-\d{4}$") Then
    MessageBox.Show("Not a valid phone number")
End if

Example program ValidatePhone, which is available for download on the book’s website, ...

Get Visual Basic 2012 Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.